【发布时间】:2019-02-18 09:39:11
【问题描述】:
template<typename... ArgTypes>
int add(ArgTypes... args);
template<typename T, typename... ArgTypes>
int add(T t, ArgTypes... args)
{
int sum = 0;
return t + add(args...);
}
template<> int add() {
return 0;
}
如何添加更多的运算,例如乘法和减法? template<> int add() 是什么意思?
谁能详细解释一下这个递归模板是如何工作的?
UPD:谢谢你们关于减法,是的,减法不是可交换的,所以它并不适合这种递归模板。
【问题讨论】:
-
template<>代表template specialization。 -
摆脱“递归”:
template<typename... ArgTypes> int add(ArgTypes... args) { return (0 + ... + args); }(C++17)。 -
@Jarod42 谢谢,我可以保留递归并添加其他操作吗?也许使用类模板?
-
请注意,如果以
add(1.1, 2.2, 3.3);调用这些函数会产生大量(可能)不需要的转换 - 结果将是 6,因为特化强制所有后续操作数的隐式转换。 -
还要注意,如果你的目标是混淆,你所做的只是让你的代码更难自己阅读,而不是让机器更难理解。除非您在没有优化的情况下发布代码,否则编译器只会消除所有这些递归调用并用一些简单的指令替换它。
标签: c++ templates recursion variadic-templates template-specialization