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

标签 c++ templates parameters

最近,我了解了非类型引用参数,如 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!也欢迎其他答案!

最佳答案

不,All the standard requires is that the observable behavior be as if the templates were instantiated before the program started to run. .

输出原因 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
}

live demo

感谢 Guillaume Racicot 的评论,以下是错误的。

a 初始化为 0编译时并在运行时修改。 Ntemp0 更改为(编译时)到5 (运行时)。

更新:

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

关于c++ - 非类型引用参数可以在运行时修改,是否意味着模板可以在运行时实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732713/

相关文章:

c++ - 实现仅在特定条件下定义的 typedef

C++ 中的类 Java 注释

c++ - 使用非专用模板化类型作为模板参数

c++ - 模板, 'operator<<' 'out << "中的 ("' 不匹配

android - 使用 OpenCV 3.1 在 Android Studio 1.5 中开发原生 C++ 应用程序

c++ - 从标记的姿势相机的姿势

c++ (g++-4.x) 模板问题

C - 无法初始化作为参数传递的指针

javascript - 为要使用的 jquery 函数添加多个参数的正确方法

c++ - SQLBindParameter 返回 -1