For templates with untyped parameters, why are arguments bound to pointers or referencing untyped parameters required to have a static lifetime?

it is mentioned on page 580 of the fifth edition of cPP primer that an argument bound to an untyped integer parameter must be a parameter expression. Arguments bound to pointers or references to untyped parameters must have a static lifetime.
the content of cPP is too much to remember. I want to know why cPP is set in this way.

CPP
Jul.06,2021

are you talking about untyped template parameters? Because template parameters need to be determined at compile time, not at run time, arguments bound to untyped template parameters must be an expression that can be determined at compile time, not an object that can be dynamically generated at run time. The so-called static lifetime is the same, which is something that must be determined at compile time, not at run time.

for example, the following code is feasible:

template <std::string * temp>
void f()
{
   cout << *temp << endl;
}

template <std::string & temp>
void g()
{
     cout << temp << endl;
     temp += "...appended some string";
}

std::string s;

int main() {
        s = "can assign values locally";
        f<&s>();
        g<s>();
        cout << s << endl;
        return 0;
}

because the template parameters here refer to pointers, and s is a variable defined outside the main function, its address can be determined at compile time, so it can be executed normally.

but the following code is wrong:

template <std::string temp>
void f()
{
     // ...
}

int main() {
        std::string s = "can assign values locally";
        f<s>();
        cout << s << endl;
        return 0;
}

because s is a local variable here, the address is generated temporarily every time the compilation is executed, and there is no way to replace the above template parameters, so it is illegal.

Menu