Tell me how to solve with the help of LAMBA-EXPRESSION problem: Write a function that calculates the sum of a list of arguments of arbitrary length with different types of list elements.

#include <iostream> #include <utility> #include<functional> template <class T> T sum(T&& t) { return t; } template <class T, class... Args> auto sum(T&& t, Args&&... args)->decltype(t + sum(std::forward<Args> args)...)) { return (t + sum(std::forward<Args>(args)...)); } template <class T, class... Args> using KUnaryType = std::function < T(T, Args...) >; int main() { auto h = sum(2, 2.5, ' ', false); std::cout << h << std::endl; return 0; } 

Code without lambda expression.

  • one
    And show the code that you have at the moment. - VladD September
  • #include <iostream> #include <utility> #include <functional> template <class T> T sum (T && t) {return t; } template <class T, class ... Args> auto sum (T && t, Args && ... args) -> decltype (t + sum (std :: forward <Args> (args) ...)) {return ( t + sum (std :: forward <Args> (args) ...)); } template <class T, class ... Args> using KUnaryType = std :: function <T (T, Args ...)>; template <class T, class ... Args> KUnaryType <T, Args ...> My_sum = [] () {}; int main () {auto h = sum (2, 2.5, '', false); std :: cout << h << std :: endl; return 0; } - user220297 September
  • There is a question to edit button, better enter the question. - VladD September

1 answer 1

I came up with this option ...

 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; } 

Yes, the templates + lambdas are more abruptly than the cardinal and haberdasher :)

And no description of the return type in the spirit of the solution to this question .

  • Harry, you are super! - user220297