具有引用模板参数的函数模板
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;
}
编译过程中出现编译器错误:
$ 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)
一样调用它。
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 具有常量引用参数的函数模板专用化
- 使用可变参数函数作为模板参数
- std::span<const T> 作为函数模板中的参数
- 如何在C++中伪造虚拟可变参数函数模板?
- C++ std::functional 中的可变参数函数模板
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 三个参数函数模板令人困惑的示例
- 父可变参数函数模板专门用于子级
- C++如何将可变参数函数模板的参数包 -> 包装到 lambda 中
- 将函数传递给可变参数函数模板
- 为什么可变参数函数模板中的这个 constexpr 不是常数?
- 将多个初始值设定项列表传递到可变参数函数模板时遇到问题
- 依赖类型不明确的 c++11 可变参数函数模板重载是否不明确
- 操作可变参数函数模板的函数参数
- C++11 中的非类型可变参数函数模板
- 将可变参数函数模板的每个参数传递给返回void的函数
- 包扩展不在最后一个参数中的可变参数函数模板
- 将可变参数函数模板参数存储到联合向量中的最有效方法
- Clang 和 GCC 在解决可变参数函数模板重载时的行为不同