简体   繁体   中英

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

Recently, I learned about non-type reference parameters like template<auto& t> . Then I find that t can be modified at run-time:

#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';
}

The output is 5 , not 2 . Does it mean temp is instantiated at run-time?


I will try to answer my own question. If anywhere wrong, please correct me, thx! Other answers also welcome!

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

The reason for the output 5 is that reference type auto & here just means

  • N will bind with a when being instantiated and
  • the instantiation still occurs at compile-time .

Look at this:

#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

Thanks for Guillaume Racicot's comment, the below is wrong.

a is initialized with 0 at compile-time and modified at run-time . N in temp changed from 0 ( compile-time ) to 5 ( run-time ).

Update:

In many implementations, a is stored in bss segment and will be initialized to zero or do not have explicit initialization in the source code by crt0 at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM