3

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!

Chen Li
  • 4,824
  • 3
  • 28
  • 55
  • 1
    Informally, the template argument is the location of `a`, not the stored value. The location of non-local variables is considered to be known at compile-time. The code would stop working if you moved `int a = 2;` inside `main` – M.M Jun 07 '18 at 04:00
  • Thanks, @M.M So, the external linkage is required, right? – Chen Li Jun 07 '18 at 04:05
  • Not sure off the top of my head – M.M Jun 07 '18 at 04:06
  • https://stackoverflow.com/a/5687575/6949852 find the requirement for linkage – Chen Li Jun 07 '18 at 04:11

1 Answers1

0

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.

Chen Li
  • 4,824
  • 3
  • 28
  • 55