From Lippman et al C++Primer 5th edition, section 16.1.2:
//forward declarations needed for friend declarations in Blob
template <typename> class BlobPtr;
template <typename> class Blob;
template <typename T> bool operator==(const Blob<T>&, const Blob<T>&)
template <typename T> class Blob {
friend class BlobPtr<T>;
friend bool operator==<T>(const Blob<T>&, const Blob<T>&);
}
First question: in the line
friend bool operator==<T>(const Blob<T>&, const Blob<T>&);
why is the <T>
present after ==
? Why not simply write
friend bool operator==(const Blob<T>&, const Blob<T>&);
I added the following code to define operator== and to instantiate the class template. It successfully compiles and links:
template <typename T>
bool operator==(const Blob<T> &lhs, const Blob<T> &rhs) {return true;}
int main() {
Blob<int> a, b;
a == b;
}
If I remove the <T>
following operator==
in the friend declaration, I get a linker error:
Undefined symbols for architecture x86_64: "operator==(Blob<int> const&, Blob<int> const&)", referenced from: _main in partial_blob-3ccda9.o
Clearly the <T>
following operator==
is necessary, but why?
Second question: If I want to define the relational less than operator <
for the same class, I would guess that I should follow the pattern that worked for ==
:
1) forward-declare the operator
2) declare the operator as a friend, inserting the additional <T>
whose function I don't understand
3) define the operator out-of-class.
I therefore add the following code:
template <typename T> bool operator<(const Blob<T>&, const Blob<T>&);
template <typename T> class Blob {
//other members as before
friend bool operator<<T>(const Blob<T>&, const Blob<T>&);
}
bool operator<(const Blob<T>&, const Blob<T>&) {return true;}
int main() {
//other statements as before
a < b;
}
This produces a compilation error around operator<<T>
, I think because the compiler interprets <<
as the insertion operator. But if I rewrite the friend declaration as
friend bool operator<(const Blob<T>&, const Blob<T>&);
then I get a linker error similar to the earlier linker error with ==
:
"operator<(Blob<int> const&, Blob<int> const&)", referenced from: _main in partial_blob-a85d5d.o
How can I successfully define operator <
for this class?
(Note: the operators must be declared as friends because more fully-realized implementations rely on private variables.)