非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
Non-type reference parameter can be modified at run-time, does it mean template can be instantiated at run-time?
最近,我了解了非类型引用参数,如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
感谢纪尧姆·拉西科特的评论,以下是错误的。
0
初始化,并在运行时进行修改。N
temp
从0
(编译时(更改为5
(运行时(。更新:
在许多实现中,a
存储在bss
段中,并且将被初始化为零,或者在运行时通过crt0
在源代码中没有显式初始化。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我在c++代码中生成了一个运行时#3异常
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 建议在运行时将带有类实例的列表从c++导入qml
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 读取文件时运行时的未知行为
- 函数在Windows或Linux上运行时表现不同
- 在声明中合并两个常量"std::set"(不是在运行时)
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 编译器优化合并了相同的函数实现,这意味着在运行时要绕过存根
- 当我的应用程序无法在调试模式下运行,但 exe 文件可以完美运行时,这意味着什么?