Reputation: 1125
I am trying to overload the '+'
operator for a class template but getting unresolved external symbol error calling it using the infix notation:
// 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
}
It works fine for regular non-templated classes so wondering if it is possible to achieve the same thing here.
I'm using Visual C++ 2015.
Upvotes: 3
Views: 931
Reputation: 217235
friend B operator+(B const &lhs, B const &rhs);
is a non template function.
The simpler would be to define it 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_;
};
Else you have to declare all template friend
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_;
};
or just the specific one
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_);
}
Upvotes: 4
Reputation: 1740
You have not defined it as a template inside the class. The simplest solution is defining the function inside the class (inline):
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_;
};
Upvotes: 0