在模板类之外重载操作

时间:2016-05-26 23:02:12

标签: c++ templates operator-overloading

如果我有一个带有重载赋值运算符的类,如下所示:

template<typename T> class Foo {
private:
     T var;
public:
    T operator=(T v){var = v;};
};

它有效,但是如果我想在类之外定义运算符,它告诉我T不是一个类型(它是正确的)。我怎样才能绕过这个并在课堂外定义它?

1 个答案:

答案 0 :(得分:0)

您可以按如下方式在类之外定义它:

template<typename T>
Foo<T>& Foo<T>::operator=(T v)
// Note the Foo& that was added (it needs to be added to the declaration too)
// This is the idiomatic way to implement the assignment operator
{
    var = v;
    return *this;
}