简体   繁体   中英

Constant variable cannot be template parameter for reference, but non-const can

There is this code:

#include <iostream>

template<const double& f>
void fun5(){
    std::cout << f << std::endl;
} 

//const double dddd = 5.0; error: ‘dddd’ cannot appear in a constant-expression
//however it works for extern const double dddd = 5.0;

double dddd = 5.0; // works

int main() 
{ 
    fun5<dddd>();
    return 0;
} 

const double dddd doesn't work as template parameter (however extern const double dddd works). double dddd works, but it is not constant. What is difference between extern const double and const double variables defined in global scope?

const gives variables internal linkage by default, while both extern and non-const do not. Internal linkage symbols are expressly prohibited from being template parameters by the standard (pre-C++11, I know a few things changed there).

When you put in the expression:

const double dddd = 5.0;

Effectively you are aliasing dddd to be 5.0 and there is no variable there at all, it can be used as a constant and therefore has no address. You would be able to pass it to a function that takes a const reference because the parameter itself is a variable, ie it has a space on the stack, you can take its address. You cannot do that with a constant. There is no &dddd in your code.

If you make it extern, it does actually turn into a "proper" variable that occupies memory and has an address. It is immutable but it is not a constant.

(Essentially the compiler is allowed to eliminate dddd and substitute it for 5.0 anywhere in the code. This is internal linkage ).

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