【发布时间】:2020-03-25 10:18:20
【问题描述】:
如何使用通过引用传递的参数显式实例化模板函数?
我有一个简单的模板函数,它可以接受任何类型并将其转换为字符串:
template <typename T>
string to_string (const T &e) {
std::stringstream ss;
string str;
ss << e;
ss >> str;
return str;
}
注意参数参数e是通过引用传递的。
我现在想为不同的数据类型显式实例化函数,例如:
template string to_string<string> (string);
template string to_string<double> (double);
但是,编译器抱怨(由于显式实例化):
错误:“to_string”的显式实例化不引用函数模板、变量模板、成员函数、成员类或静态数据成员
模板字符串 to_string(string);
如果我将模板函数的参数从 const T &e 更改为 const T e - 即删除引用 - 它可以编译并正常工作。
如何使用通过引用传递的参数显式实例化模板函数?
工具链:
- C++14
- clang 版本 11.0.0 (MacOS)
【问题讨论】:
-
不要使用
using namespace std;,因为有std::to_string函数 -
T和const T是等效的参数类型。T和const T&不是。
标签: c++ templates clang c++14 pass-by-reference