Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将变量作为参数传递到c++;模板_C++_C++11_Templates_Constexpr - Fatal编程技术网

C++ 将变量作为参数传递到c++;模板

C++ 将变量作为参数传递到c++;模板,c++,c++11,templates,constexpr,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()

我正在尝试实现以下函数调用:

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);
    }
}
模板
作废打印(){

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

详细回答:问题在于
constepr
函数在编译时工作,当can(当输入是know compile time)和must(当返回的值必须是已知的编译时模板值或初始化
constepr
值时)。编译器也可以选择在不需要时计算值编译时间,但在不知道编译时间时无法编译

所以您的
constexpr
函数

constexpr int getConstexpr(int a) {
     return a;
}
函数中调用到模板()

从C++17开始,您可以使用模板折叠和简化
foo()
,避免丑陋的
未使用的部分,如下所示

template <int ... Is>
void foo (std::integer_sequence<int, Is...> const &)
 { (print<Is>(), ...); }
模板
void foo(std::integer\u sequence const&)
{(print(),…);}

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

详细回答:问题在于
constepr
函数在编译时工作,当can(当输入是know compile time)和must(当返回的值必须是已知的编译时模板值或初始化
constepr
值时)。编译器也可以选择在不需要时计算值编译时间,但在不知道编译时间时无法编译

所以您的
constexpr
函数

constexpr int getConstexpr(int a) {
     return a;
}
函数中调用到模板()

从C++17开始,您可以使用模板折叠和简化
foo()
,避免丑陋的
未使用的部分,如下所示

template <int ... Is>
void foo (std::integer_sequence<int, Is...> const &)
 { (print<Is>(), ...); }
模板
void foo(std::integer\u sequence const&)
{(print(),…);}

这根本不可能。模板是仅编译时构造。非contexpr函数的参数在运行时传递,这可能会在编译后很长一段时间内发生。为什么要这样做?这根本不可能。模板是仅编译时构造。非contexpr函数的参数在运行时传递,这可能会导致编译后很久才出现。为什么要这样做?