通过引用传递参数时模板的显式实例化
Explicit instantiation of template when passing argument by reference
如何使用通过引用传递的参数显式实例化模板函数?
我有一个简单的模板函数,它接受任何类型并将其转换为字符串:
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);
然而,编译器抱怨(由于显式实例化):
error: explicit instantiation of 'to_string' does not refer to a function template, variable template, member function, member class, or static data member
template string to_string (string);
如果我将模板函数的参数从 const T &e
更改为 const T e
- 即删除引用 - 它编译并工作正常。
如何使用通过引用传递的参数显式实例化模板函数?
工具链:
- C++14
- clang 版本 11.0.0 (MacOS)
您也应该在显式实例化中将参数指定为引用。否则它们将不匹配函数模板的签名。例如。如果 T
是 double
,那么参数类型 const T&
应该是 const double&
.
template string to_string<string> (const string&);
template string to_string<double> (const double&);
如何使用通过引用传递的参数显式实例化模板函数?
我有一个简单的模板函数,它接受任何类型并将其转换为字符串:
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);
然而,编译器抱怨(由于显式实例化):
error: explicit instantiation of 'to_string' does not refer to a function template, variable template, member function, member class, or static data member
template string to_string (string);
如果我将模板函数的参数从 const T &e
更改为 const T e
- 即删除引用 - 它编译并工作正常。
如何使用通过引用传递的参数显式实例化模板函数?
工具链:
- C++14
- clang 版本 11.0.0 (MacOS)
您也应该在显式实例化中将参数指定为引用。否则它们将不匹配函数模板的签名。例如。如果 T
是 double
,那么参数类型 const T&
应该是 const double&
.
template string to_string<string> (const string&);
template string to_string<double> (const double&);