具有引用模板参数的函数模板

Function template with reference template parameter

本文关键字:参数 函数模板 引用      更新时间:2023-10-16

有这样的代码:

#include <iostream>
template<const double& f>
void fun5(){
    std::cout << f << std::endl;
} 
int main() 
{ 
    const double dddd = 5.0;
    fun5<dddd>();
    return 0;
} 

编译过程中出现编译器错误:

$ 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"作为模板参数不起作用?应该做些什么才能使其起作用?

模板参数的引用和指针必须具有外部链接(对于C++11,或内部链接,但需要静态存储持续时间)。因此,如果必须使用dddd作为模板参数,则需要将其移动到全局范围并使其成为extern:

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

您可能误解了模板的用途。模板参数(尖括号之间的东西)应该是类型或整数(尽管有些实现允许浮点类型)。

在您的情况下,最好将fun5声明为void fun5(double& f),并像fun5(dddd)一样调用它。