将变量作为参数传递给c ++模板

时间:2018-06-03 12:43:00

标签: c++ c++11 templates constexpr

我试图实现以下函数调用:

template<int index>
void print() {
    std::cout << index;
}

constexpr int getConstexpr(int a) {
     return a;
}

void function_to_template(int i) {
    const int j = getConstexpr(i);
    print<j>();
}

void main() {
    for(int = 0 ; i < 10; i++) {
       function_to_template(i);
    }
}

我收到以下错误:

  

致命错误:没有匹配的成员函数来调用&#39; print&#39;。

任何我想知道如何在c ++模板中传递变量作为参数?

感谢。

1 个答案:

答案 0 :(得分:3)

简短回答:您的代码不起作用,因为无法将运行时变量作为模板参数传递

答案很长:问题是RowExpander函数在可以编译的时候(当输入知道编译时)并且必须(当返回的值必须作为模板值或初始化时编译时)一个constexpr值。编译器可以选择在没有必要的情况下计算值编译时间,但是当编译时间不知道时无法编译它。

所以你的constexpr功能

constexpr

constexpr int getConstexpr(int a) { return a; }

中调用
function_to_template()

是计算运行时(非编译时),因为void function_to_template(int i) { const int j = getConstexpr(i); print<j>(); } 是运行时值。

如果要实现一种编译时i,则应使用标准模板工具(从C ++ 14开始)或模拟它们(在C ++ 11中)。我的意思是:forstd::make_integer_sequence

以下是一个完整的编译示例,显示我的意思

std::integer_sequence

从C ++ 17开始,您可以使用模板折叠并简化#include <utility> #include <iostream> template <int index> void print () { std::cout << index; } template <int ... Is> void foo (std::integer_sequence<int, Is...> const &) { using unused = int[]; (void)unused { 0, (print<Is>(), 0)... }; } int main () { foo(std::make_integer_sequence<int, 10>{}); } ,避免丑陋的foo()部分,如下所示

unused
相关问题