Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c++ - Function template with reference template parameter

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...