ham*_*els 0 c++ templates metaprogramming template-meta-programming
我尝试将另一个模板参数添加到元编程的阶乘示例中.但以下不起作用.什么是正确的方法?
码:
#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);
}
Run Code Online (Sandbox Code Playgroud)
错误:
test4.cpp(9): error: an explicit template argument list is not allowed on this declaration
inline void loop<T, 0>(T i){
Run Code Online (Sandbox Code Playgroud)
您不能部分专门化功能模板.完全停止.
在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);
}
}
Run Code Online (Sandbox Code Playgroud)
在那之前,我建议只把深度作为一个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>{} );
}
Run Code Online (Sandbox Code Playgroud)