gpt4 book ai didi

c++ - 通过引用传递参数时模板的显式实例化

转载 作者:行者123 更新时间:2023-12-01 15:13:21 25 4
gpt4 key购买 nike

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

我有一个简单的模板函数,它接受任何类型并将其转换为字符串:

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)
  • 最佳答案

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

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

    关于c++ - 通过引用传递参数时模板的显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60846758/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com