Got just such a puzzle:

Write a function that calculates the sum of a list of arguments of arbitrary length with different types of list elements.

I do not know how to transfer to the function an arbitrary number of elements, especially of different types.

  • In addition, I have a problem in processing this arbitrary number of arguments. It is not clear how to drive them into the cycle. - Nikita Savanovich
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • If you are still interested, look at one more solution - in the Update of my answer ... - Harry

2 answers 2

An arbitrary number of arguments can be passed using a triple-point. How to iterate over all arguments, see here . But to use this solution, you need to know the types of arguments, because it does not suit you. The variadic templates that appeared in C ++ 11 will help you. Enumerating all the arguments with a cycle does not work, you need recursion:

#include <iostream> template<class R, class T> R summ(const T &arg){ return arg; } template<class R, class T, class ...Args> R summ(const T &arg, const Args &...args){ return summ<R>(args...) + arg; } int main(){ char c = 1; short s = 2; int i = 3; double d = 4; long l = 5; std::cout << summ<int>(c, s, i, d, l); //15 } 

    Is that such a horror?

     template <typename ...P> struct sum_type; template <typename T> struct sum_type<T> { using type = T; }; template <typename T, typename ...P> struct sum_type<T, P...> { using type = decltype(T()+typename sum_type<P...>::type()); }; template <typename ...P> using sum_type_t = typename sum_type<P...>::type; template <typename T> inline T sum(T t) { return t; } template <typename T, typename ...P> inline sum_type_t<T, P... > sum(T t, P... p) { return t + sum(p...); } 

    Peeped in Discovering Modern C ++.

    You can simply transfer anything to the function using three points :) - of type sum(double a, ...) , but I don’t recognize such a possibility within the function to recognize different types without templates.

    Update Here is another solution:

     template <typename T> inline T sum(T t) { return t; } template <typename T, typename ...P> inline auto sum(T t, P... p) { return [](auto a, auto b) { return a + b; }(t,sum(p...)); } int main() { std::cout << sum(2, 2.5, ' ', false) << std::endl; }