c++ - 具有一个显式参数的模板

标签 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);
}

错误:

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/

相关文章:

ruby - 在 rspec 中定义 `after` 别名的正确方法是什么?

c++ - 我如何将一个大型的、经常使用的 C++ 宏转换为一个 C++ 模板或类似的?

c++ - boost spirit 解析器前瞻解析

Python错误:No constructor defined in SWIG generated module of C++ templated code

C++ 可变参数模板移除函数逻辑

c++ - 为什么我不能使用模板模板参数将 std::vector<MyType> 传递给此函数?

c++ - 如果 constexpr 格式正确,这是在内部使用 static_assert 吗?

C++ 预处理器意外编译错误

c++ - 如何使模板函数成为模板类的 friend

C++ 元模板 : A Good or Bad Design Choice?