【问题标题】:Explicit instantiation of template when passing argument by reference通过引用传递参数时模板的显式实例化
【发布时间】: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 &amp;e 更改为 const T e - 即删除引用 - 它可以编译并正常工作。

如何使用通过引用传递的参数显式实例化模板函数?

工具链:

  • C++14
  • clang 版本 11.0.0 (MacOS)

【问题讨论】:

  • 不要使用using namespace std;,因为有std::to_string函数
  • Tconst T 是等效的参数类型。 Tconst T&amp; 不是。

标签: c++ templates clang c++14 pass-by-reference


【解决方案1】:

您也应该在显式实例化中指定参数作为参考。否则它们将与函数模板的签名不匹配。例如。如果Tdouble,那么参数类型const T&amp;应该是const double&amp;

template string to_string<string> (const string&);
template string to_string<double> (const double&);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2011-10-16
    • 2016-10-10
    • 2021-09-21
    相关资源
    最近更新 更多