最近,我了解了非类型引用参数,如 template<auto& t>
.
然后我发现 t
可以在运行时修改:
#include <iostream>
template<auto& N>
struct X{
int operator()() { return N; }
};
int a = 2;
int main()
{
std::cin >> a; //stdin: 5
auto temp = X<a>();
std::cout << temp() << '\n';
}
输出是5
, 不是 2
.是不是表示temp
在运行时实例化?
我将尝试回答我自己的问题。如有不妥之处请指正,thx!也欢迎其他答案!
最佳答案
输出原因 5
是引用类型 auto
& 这里只是意味着
-
N
将与a
绑定(bind)当被实例化和 - 实例化仍然发生在
compile-time
.
看看这个:
#include <iostream>
template<auto& N>
struct X{
int operator()() { return N; }
};
int a;
int main()
{
auto temp = X<a>();
std::cout << "Compile-time: " << temp() << '\n'; //output 0
std::cin >> a; //stdin: 5
std::cout << "Run-time: " << temp() << '\n'; //output 5
}
感谢 Guillaume Racicot 的评论,以下是错误的。
a 初始化为 0
在编译时并在运行时修改。 N
在 temp
从 0
更改为(编译时)到5
(运行时)。
更新:
在许多实现中,a
存储在 bss
段,将被初始化为零或在源代码中没有显式初始化 crt0
在运行时。
关于c++ - 非类型引用参数可以在运行时修改,是否意味着模板可以在运行时实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732713/