下面的代码适用于:左关联求和运算的目标:sum(1,2,3,4);
sum(1,2,3,4,5)
但是,它对于or将无法正常工作 sum(1,2,3,4,5,...)
。任何超过 4 个参数的东西都会产生错误:
错误:没有匹配函数调用 sum(int, int, int, int, int)
==================================
template <typename T>
T sum(const T& v) {
return v;
}
template <typename T1, typename T2>
auto sum(const T1& v1, const T2& v2) -> decltype( v1 + v2) {
return v1 + v2;
}
template <typename T1, typename T2, typename... Ts>
auto sum(const T1& v1, const T2& v2, const Ts&... rest) -> decltype( v1 + v2 + sum(rest...) ) {
return v1 + v2 + sum(rest... );
}
int main() {
cout << sum(1,2,3,4); //works correctly
//cout << sum(1,2,3,4,5); //compile error
}