From 452995c0937ea25c8321ff3841e123c7374f99fb Mon Sep 17 00:00:00 2001 From: Eric Floyd Date: Thu, 1 Aug 2024 13:40:13 -0400 Subject: [PATCH] fixed arrayElement overloads --- include/faker-cxx/helper.h | 26 +++++++++++++++++++++++--- include/faker-cxx/word.h | 7 ++++--- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/include/faker-cxx/helper.h b/include/faker-cxx/helper.h index 8effb9ee..1429b3b9 100644 --- a/include/faker-cxx/helper.h +++ b/include/faker-cxx/helper.h @@ -49,8 +49,8 @@ T arrayElement(const std::array& data) return data[index]; } -template -auto arrayElement(It start, It end) -> decltype(*::std::declval()) +template +auto arrayElement(It start, It end) -> It::range_difference_t { auto size = static_cast(end - start); @@ -61,7 +61,27 @@ auto arrayElement(It start, It end) -> decltype(*::std::declval()) const std::integral auto index = number::integer(size - 1); - return *(start + static_cast>(index)); + return start[index]; +} + +template +auto arrayElement(It start, It end) +{ + auto size = std::distance(start, end); + + if (size == 0) + { + throw std::invalid_argument{"Range [start,end) is empty."}; + } + + const std::integral auto index = number::integer(static_cast(size - 1)); + + std::input_iterator auto dummyIterator = start; + + for (size_t i = 0; i < index; i++) + dummyIterator++; + + return *dummyIterator; } /** diff --git a/include/faker-cxx/word.h b/include/faker-cxx/word.h index 854fec0f..d7072fc9 100644 --- a/include/faker-cxx/word.h +++ b/include/faker-cxx/word.h @@ -4,8 +4,8 @@ #include #include #include -#include "faker-cxx/export.h" +#include "faker-cxx/export.h" #include "faker-cxx/helper.h" namespace faker::word @@ -144,8 +144,9 @@ FAKER_CXX_EXPORT std::string_view preposition(std::optional length = s */ FAKER_CXX_EXPORT std::string_view verb(std::optional length = std::nullopt); -template -auto sortedSizeArrayElement(std::optional length, It start, It end) -> decltype(*std::declval()) +template +auto sortedSizeArrayElement(std::optional length, It start, It end) -> + typename std::iterator_traits::value_type { if (!length) {