有这个代码:
#include <iostream>
template<const double& f>
void fun5(){
std::cout << f << std::endl;
}
int main()
{
const double dddd = 5.0;
fun5<dddd>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译期间编译器错误:
$ 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()
Run Code Online (Sandbox Code Playgroud)
为什么将'dddd'作为模板参数放置不起作用,应该怎样做才能使其工作?
模板参数的引用和指针必须具有外部链接(或内部链接,对于C++ 11,但需要静态存储持续时间).因此,如果必须将其dddd用作模板参数,则需要将其移至全局范围并进行以下操作extern:
extern const double dddd = 5.0;
int main()
{
fun5<dddd>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)