I'm currently reading Effective C ++, and there is a chapter that contains code similar to this:
template <typename T> class Num { public: Num(int n) { ... } }; template <typename T> Num<T> operator*(const Num<T>& lhs, const Num<T>& rhs) { ... } Num<int> n = 5 * Num<int>(10);
The book says that this will not work (and it really is not), because you cannot expect the compiler to use implicit typecasting to specialize the template.
As a permission, it is proposed to use the "friend" syntax to define a function within a class.
//It works template <typename T> class Num { public: Num(int n) { ... } friend Num operator*(const Num& lhs, const Num& rhs) { ... } }; Num<int> n = 5 * Num<int>(10);
And the book suggests using this declaration to declare when I need an implicit conversion to a template class type. And all this makes sense.
But why can't I get the same example that works with a generic function, not an operator?
template <typename T> class Num { public: Num(int n) { ... } friend void doFoo(const Num& lhs) { ... } }; doFoo(5);
This time, the compiler complains that it cannot find doFoo at all. And if I declare doFoo outside the class, I get a reasonable error of inappropriate types. It seems that the "friend ..." part is simply ignored.
So is there a problem with my understanding? What is the difference between a function and an operator in this case?
c ++ templates
user1835359
source share