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函数的参数在运行时传递,这可能会导致编译后很久才出现。为什么要这样做?