非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?

Non-type reference parameter can be modified at run-time, does it mean template can be instantiated at run-time?

本文关键字:运行时 意味着 实例化 是否 修改 引用 类型 参数      更新时间:2023-10-16

最近,我了解了非类型引用参数,如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在运行时实例化?


我会试着回答我自己的问题。如果有什么错误,请纠正我,谢谢!其他答案也欢迎!

不,所有标准要求是可观察的行为就像 模板在程序开始运行之前实例化。 .

输出5的原因是引用类型auto,这里只是意味着

  • N在实例化时将与a绑定,并且
  • 实例化仍然发生在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
}

live demo

感谢纪尧姆·拉西科特的评论,以下是错误的。

a 在编译时使用0初始化,并在运行时进行修改。Ntemp0(编译时(更改为5(运行时(。

更新:

在许多实现中,a存储在bss段中,并且将被初始化为零,或者在运行时通过crt0在源代码中没有显式初始化。