Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There is this code:

#include <iostream>

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

int main() 
{ 
    const double dddd = 5.0;
    fun5<dddd>();
    return 0;
} 

Compiler error during compilation:

$ g++ klasa.cpp -o klasa
klasa.cpp: In function ‘int main()’:
klasa.cpp:11:10: error: ‘dddd’ cannot appear in a constant-expression
klasa.cpp:11:16: error: no matching function for call to ‘fun5()’
klasa.cpp:11:16: note: candidate is:
klasa.cpp:4:6: note: template<const double& f> void fun5()

Why placing 'dddd' as template parameter doesn't work and what should be done to make it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
380 views
Welcome To Ask or Share your Answers For Others

1 Answer

References and pointers for template arguments must have external linkage (or internal linkage, for C++11, but static storage duration is required). So if you have to use dddd as a template argument, you need to move it to global scope and make it extern:

extern const double dddd = 5.0;
int main()
{
    fun5<dddd>();
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...