C++ variadic functions

Run Settings
LanguageC++
Language Version
Run Command
#include <iostream> #include <numeric> using namespace std; /* not really *args */ template<typename T> T isum(initializer_list<T> args) { return accumulate(args.begin(), args.end(), T()); } /* template pack expansion */ template<typename T> T tsum(T v) { return v; } template<typename T, typename... Targs> T tsum(T first, Targs... rest) { return first + tsum(rest...); } /* auto (-std=gnu++2a, but glot.io's gcc 5.1 doesn't support it XD) * see https://wandbox.org/permlink/MTyYnmP8ChQvkEol */ // auto asum = [](auto... xs) { // return xs + ...; // }; /* auto (-std=c++14) */ auto asum = [](auto... values) { std::common_type_t<decltype(values)...> ret = {}; decltype(ret) _[] = { (ret += values)... }; (void)_; return ret; }; int main() { cout << isum({ 1, 2, 3 }) << endl; cout << tsum( 1, 2, 3 ) << endl; cout << asum( 1, 2, 3 ) << endl; return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines