使用 = 的模板运算符专用化

template operator specialization with =

本文关键字:运算符 专用 使用      更新时间:2023-10-16

我正在尝试实现此模板运算符专用化

template <class T>
class test
{
public:
  T value;
};

template <> test &test::operator=<std::string>(const char *rhs)
{ return *this;}

但是使用 g++,我收到此错误:

错误:在没有参数列表的情况下无效使用模板名称"test" 模板<>测试 &test::运算符=(常量字符 *rhs) ^~~~

似乎您只是将模板参数放在了错误的位置。模板化类需要其范围之外的模板参数,因此在这种情况下,返回类型也需要模板参数。

template<class T>
class test
{
public:
    test & operator=(const char * rhs) {
        return *this;
    }
};
template<> test<std::string> & test<std::string>::operator=(const char * rhs) { 
// type goes here ^^^^^^^^^ and here ^^^^^^^^^^ 
    return *this; 
}