C++ adding friend to a template class in order to typecast

Posted by user1835359 on Stack Overflow See other posts from Stack Overflow or by user1835359
Published on 2012-11-19T10:30:01Z Indexed on 2012/11/19 11:03 UTC
Read the original article Hit count: 262

Filed under:
|

I'm currently reading "Effective C++" and there is a chapter that contains code similiar 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 won't work (and indeed it doesn't) because you can't expect the compiler to use implicit typecasting to specialize a template.

As a soluting it is suggested to use the "friend" syntax to define the function inside the 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 to use this friend-declaration thing whenever I need implicit conversion to a template class type. And it all seems to make sense.

But why can't I get the same example working with a common 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 complaints that he can't find any 'doFoo' at all. And if i declare the doFoo outside the class, i get the reasonable mismatched types error. Seems like the "friend ..." part is just being ignored.

So is there a problem with my understanding? What is the difference between a function and an operator in this case?

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates