33 lines
794 B
C++
33 lines
794 B
C++
|
#include <iostream>
|
||
|
// compile using std=c++1z-option
|
||
|
// tested with clang++ and g++
|
||
|
// using:
|
||
|
// $CC -Wall -Werror -pedantic -pedantic-errors -std=c++1z -o $OUT $IN
|
||
|
|
||
|
/* "Old" code:
|
||
|
* The usage of auto to implicitly get the return type is C++17,
|
||
|
* the main part is using C++11 variadic templates and overloading
|
||
|
*/
|
||
|
auto sum1() { return 0;}
|
||
|
|
||
|
template<typename T>
|
||
|
auto sum1(T t) { return t; }
|
||
|
|
||
|
template<typename T, typename... Ts>
|
||
|
auto sum1(T t, Ts... ts) {return t + sum1(ts...);}
|
||
|
|
||
|
/* New code:
|
||
|
* Using c++17 fold expressions, this gets way shorter and
|
||
|
* less error prone
|
||
|
*/
|
||
|
template <typename... T >
|
||
|
auto sum2 (T... args){
|
||
|
return (... + args);
|
||
|
}
|
||
|
|
||
|
int main() {
|
||
|
std::cout << sum1(1,2,3,4,5,6,7,8,9,10) << std::endl;
|
||
|
std::cout << sum2(1,2,3,4,5,6,7,8,9,10) << std::endl;
|
||
|
return 0;
|
||
|
}
|