我尝试将另一个模板参数添加到元编程的阶乘示例中。但以下不起作用。正确的做法是什么?
代码:
#include <iostream>
template <typename T, int Depth>
inline void loop(T i){
std::cout << i;
loop<T, Depth-1>(i - 1);
}
template <typename T, int Depth>
inline void loop<T, 0>(T i){
std::cout << i << std::endl;
}
int main(void){
int i = 10;
loop<int, 3>(i);
}
错误:
test4.cpp(9): error: an explicit template argument list is not allowed on this declaration
inline void loop<T, 0>(T i){
最佳答案
您不能部分特化函数模板。句号。
在 C++17 中,您将能够编写:
template <typename T, int Depth>
inline void loop(T i){
std::cout << i;
if constexpr (Depth > 0) {
loop<T, Depth-1>(i - 1);
}
}
在那之前,我建议只将深度作为 integral_constant
参数:
template <typename T>
inline void loop(T i, std::integral_constant<int, 0> ) {
std::cout << i << std::endl;
}
template <typename T, int Depth>
inline void loop(T i, std::integral_constant<int, Depth> ){
std::cout << i;
loop(i - 1, std::integral_constant<int, Depth-1>{} );
}
关于c++ - 具有一个显式参数的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39752396/