未解析的外部符号错误重载操作符+模板

Unresolved external symbol error overloading operator+ template

本文关键字:重载 操作符 模板 错误 符号 外部      更新时间:2023-10-16

我试图重载'+'操作符为类模板,但得到无法解决的外部符号错误调用它使用中义符号:

// In main.cpp
template<class T>
struct B
{
    B(T t) : t_(t) {}
    friend B operator+(B const &lhs, B const &rhs);
    T t_;   
};
template<class T>
B<T> operator+(B<T> const &lhs, B<T> const &rhs)
{
    return B<T>(lhs.t_ + rhs.t_);
}
int main()
{
    B<int> b = 1;
    b = operator+<int>(b, 2); // works but clunky syntax
    // b = b + 2; // LNK2019: unresolved external symbol
}

对于普通的非模板化类它工作得很好,所以想知道是否有可能在这里实现同样的事情。

friend B operator+(B const &lhs, B const &rhs);

是一个非模板函数

更简单的定义是:inline:

template<class T>
struct B
{
    B(T t) : t_(t) {}
    friend B operator+(B const &lhs, B const &rhs)
    {
       return B(lhs.t_ + rhs.t_);
    }
    T t_;   
};

演示

否则你必须声明所有的模板友元

template <typename T> struct B;
template <typename T> B<T> operator+(B<T> const &lhs, B<T> const &rhs);
template<class T>
struct B
{
    B(T t) : t_(t) {}
    template <typename U>
    friend B<U> operator+(B<U> const &lhs, B<U> const &rhs);
    T t_;   
};

演示

或者只指定一个

template <typename T> struct B;
template <typename T> B<T> operator+(B<T> const &lhs, B<T> const &rhs);
template<class T>
struct B
{
    B(T t) : t_(t) {}
    friend B operator+<>(B const &lhs, B const &rhs);
    // Note the <>
    T t_;   
};
template<class T>
B<T> operator+(B<T> const &lhs, B<T> const &rhs)
{
    return B<T>(lhs.t_ + rhs.t_);
}
演示

您没有将其定义为类中的模板。最简单的解决方案是在类内部定义函数(内联):

template<class T>
struct B
{
    B (T t) : t_ (t) {}
    friend B operator+ (const B &lhs, const B &rhs)
    {
       return B (lhs.t_ + rhs.t_);
    }
    T t_;   
};