/* This is the base case */
template <typename T1, typename T2>
auto sum(const T1& v1, const T2& v2) -> decltype( v1 + v2 )
{
return v1 + v2;
}
/* And here is the recursive definition for left-associativity */
template <typename T1, typename T2, typename... Ts>
auto sum(const T1& v1, const T2& v2, const Ts&... rest) -> decltype( sum(v1 + v2, rest...) )
{
return sum(v1 + v2, rest... );
}
int main(void)
{
return sum(1, 3, 5, 7, 9, 11);
}
LyogVGhpcyBpcyB0aGUgYmFzZSBjYXNlICovCnRlbXBsYXRlIDx0eXBlbmFtZSBUMSwgdHlwZW5hbWUgVDI+CmF1dG8gc3VtKGNvbnN0IFQxJiB2MSwgY29uc3QgVDImIHYyKSAtPiBkZWNsdHlwZSggdjEgKyB2MiApCnsKICAgIHJldHVybiB2MSArIHYyOwp9CgovKiBBbmQgaGVyZSBpcyB0aGUgcmVjdXJzaXZlIGRlZmluaXRpb24gZm9yIGxlZnQtYXNzb2NpYXRpdml0eSAqLwp0ZW1wbGF0ZSA8dHlwZW5hbWUgVDEsIHR5cGVuYW1lIFQyLCB0eXBlbmFtZS4uLiBUcz4KYXV0byBzdW0oY29uc3QgVDEmIHYxLCBjb25zdCBUMiYgdjIsIGNvbnN0IFRzJi4uLiByZXN0KSAtPiBkZWNsdHlwZSggc3VtKHYxICsgdjIsIHJlc3QuLi4pICkKewogICAgcmV0dXJuIHN1bSh2MSArIHYyLCByZXN0Li4uICk7Cn0KCmludCBtYWluKHZvaWQpCnsKICAgIHJldHVybiBzdW0oMSwgMywgNSwgNywgOSwgMTEpOwp9Cg==
prog.cpp: In function ‘int main()’:
prog.cpp:17:33: error: no matching function for call to ‘sum(int, int, int, int, int, int)’
prog.cpp:17:33: note: candidates are:
prog.cpp:3:6: note: template<class T1, class T2> decltype ((v1 + v2)) sum(const T1&, const T2&)
prog.cpp:3:6: note: template argument deduction/substitution failed:
prog.cpp:17:33: note: candidate expects 2 arguments, 6 provided
prog.cpp:10:6: note: template<class T1, class T2, class ... Ts> decltype (sum((v1 + v2), sum::rest ...)) sum(const T1&, const T2&, const Ts& ...)
prog.cpp:10:6: note: template argument deduction/substitution failed:
prog.cpp: In substitution of ‘template<class T1, class T2, class ... Ts> decltype (sum((v1 + v2), rest ...)) sum(const T1&, const T2&, const Ts& ...) [with T1 = int; T2 = int; Ts = {int, int, int, int}]’:
prog.cpp:17:33: required from here
prog.cpp:10:6: error: no matching function for call to ‘sum(int, const int&, const int&, const int&, const int&)’
prog.cpp:10:6: note: candidate is:
prog.cpp:3:6: note: template<class T1, class T2> decltype ((v1 + v2)) sum(const T1&, const T2&)
prog.cpp:3:6: note: template argument deduction/substitution failed:
prog.cpp:10:6: note: candidate expects 2 arguments, 5 provided