Reputation: 42710
I try to implement the following function :
template<typename T>
class a
{
private:
T var;
friend bool operator==(const a<T> &, const a<T> &);
};
template<typename T> inline bool operator==(const a<T> &r1, const a<T> &r2)
{
return r1.var==r2.var;
}
int main () {
a<int> var0;
a<int> var1;
var0 == var1;
}
However, I get
main.obj : error LNK2001: unresolved external symbol "bool __cdecl operator==(class a<int> const &,class a<int> const &)" (??8@YA_NABV?$a@H@@0@Z)
under VC++ 2008
May I know how I can fix the linking error?
Upvotes: 1
Views: 219
Reputation: 4025
template<typename T>
class Sample
{
public:
template<typename T> friend bool operator==(const Sample<T>& lhs, const Sample<T>& rhs);
private:
T val_;
};
template<typename T>
bool operator==(const Sample<T>& lhs, const Sample<T>& rhs)
{
return lhs.val_ == rhs.val_;
}
int main()
{
Sample<char*> s1;
Sample<char*> s2;
cout << (s1 == s2) << endl;
}
Upvotes: 1
Reputation: 2778
Is there any difference between the following two implementations?
1)
template <class T>
class a ;
template <class T>
bool operator==(const a<T> &, const a<T> &);
template<typename T>
class a
{
private:
T var;
friend bool operator== <>(const a<T> &, const a<T> &);
};
template<typename T> inline bool operator==(const a<T> &r1, const a<T> &r2)
{
return r1.var==r2.var;
}
2)
template<typename T>
class a
{
private:
T var;
template <class T1>
friend bool operator==(const a<T1> &, const a<T1> &);
};
template<typename T> inline bool operator==(const a<T> &r1, const a<T> &r2)
{
return r1.var==r2.var;
}
If so, which one is preferred?
Upvotes: 0
Reputation:
What you have declares the friend op== as a non-template, but you implement it as a template. That is why the definition is not found when linking.
How I usually overload op== for class templates:
template<class T>
struct A {
friend bool operator==(A const& a, A const& b) {
return a.var == b.var;
}
private:
T var;
};
Upvotes: 3