具有参考模板参数的功能模板 [英] Function template with reference template parameter
本文介绍了具有参考模板参数的功能模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有此代码:
#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()
为什么不能将'dddd'用作模板参数,应该怎么做才能使其起作用?
Why placing 'dddd' as template parameter doesn't work and what should be done to make it work?
推荐答案
模板参数的引用和指针必须具有外部链接(对于C ++ 11,则为内部链接,但需要静态存储持续时间).因此,如果必须使用 dddd
作为模板参数,则需要将其移至全局范围并使其成为 extern
:
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;
}
这篇关于具有参考模板参数的功能模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文