我不明白为什么这并不会编译:分公司可变参数模板
#include <iostream>
template<int I1,int ...Is>
int getProdSeq() {
if(sizeof...(Is)==0)
return I1;
else
return I1*getProdSeq<Is...>();
}
int main() {
int i = getProdSeq<9,7,8>();
std::cout<<i<<std::endl;
}
在过去的递归调用函数,...IS
应该是空的,所以第一个,如果分支应采取。编译器也证实了这一点(即...IS
为空):
main.cpp: In instantiation of 'int getProdSeq() [with int I1 = 8; int ...Is = {}]':
但是编译器还吐出以下错误:
main.cpp:5:5: note: template argument deduction/substitution failed: main.cpp:10:36: note: couldn't deduce template parameter 'I1'
那么这个错误将使意义,如果函数确实用一个空的参数包进行调用,但这不应该是这样,因为我用第一个if语句规避了这个问题。为什么编译器仍在检查else分支?
因此,没有机会为这个代码工作(除非你彻底改变它),而第二个'C++ 17''constexpr'? – FloriHe
@FloriHe Sam Varshavchik已经提供了C++ 11版本。 –