代码之家  ›  专栏  ›  技术社区  ›  Chen Li

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

  •  3
  • Chen Li  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Chen Li    7 年前

    不, 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 当被实例化时
    • 实例化仍发生在 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 编译时间 修改时间 运行时间 . n 在里面 temp 从改变 ( 编译时间 ( 运行时间 )

    更新:

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