This is the follow-up question for A Summation Function For Arbitrary Nested Vector Implementation in C++. The following code is the improved version based on Zeta's answer. I am trying to enhance this the sum
function which can deal with iterable things which has begin()
and end()
(such as std::array
) of various types (such as int
, char
or unsigned int
) number. I am not familiar with the usage of std::enable_if
and std::is_arithmetic
for checking type constraint in template. If there is any possible improvement, please let me know.
template<class Container, typename = typename Container::value_type>
inline long double Sum(const Container& numbers)
{
long double sumResult = 0.0;
for (auto& element : numbers)
{
sumResult += Sum(element);
}
return sumResult;
}
template<class T,
std::enable_if_t<std::is_arithmetic<T>::value, int> = 0,
std::enable_if_t<std::is_arithmetic<T>::value, double> = 0>
T Sum(T inputNumber)
{
return inputNumber;
}
Some tests for this sum function:
int testNumber = 1;
std::vector<decltype(testNumber)> testVector1;
testVector1.push_back(testNumber);
testVector1.push_back(testNumber);
testVector1.push_back(testNumber);
std::cout << std::to_string(Sum(testVector1)) + "\n";
std::vector<decltype(testVector1)> testVector2;
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
std::cout << std::to_string(Sum(testVector2)) + "\n";
std::vector<decltype(testVector2)> testVector3;
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
std::cout << std::to_string(Sum(testVector3)) + "\n";
// std::array test case
std::array<long double, 90> numberArray;
for (size_t i = 0; i < 90; i++)
{
numberArray[i] = 1;
}
std::cout << std::to_string(Sum(numberArray)) + "\n";
The summary information:
Which question it is a follow-up to?
A Summation Function For Arbitrary Nested Vector Implementation in C++
What changes has been made in the code since last question?
The previous question focus on single type
long double
and the goal in this question is trying to deal with various type number.The previous question focus on
std::vector
and the other iterable things which hasbegin()
andend()
are considered here.The variable name has been modified in order to make better understanding.
Why a new review is being asked for?
Is it a good idea to set the type constraint like
std::enable_if_t<std::is_arithmetic<T>::value, int> = 0, std::enable_if_t<std::is_arithmetic<T>::value, double> = 0>
?
Oct 18, 2020 Update
The further implementation with c++-concepts: