Monday, January 30, 2006

having a good friend

It is always important to have a good friend. C++ has a special keyword for this purpose. Thus you sometimes read code like this:

namespace n { template<typename T> void f(T o); }
class a { friend void n::f(a); };

Is this code correct? Do you have reasons for your opinion given you have an opinion at all? Ignoring the fact whether this code is correct or not, is it smart to write code like this or is something else to be preferred? Explain.

1 comment:

Unknown said...

Shouldn't it be "class T" instead of "typename T"? AFAIK even types are called "class" in template declarations. Or maybe this is new in TR2 or whatever...

As to whether it's smart: Friend declarations are a last-ditch resort to allow tearing down access controls with tightly coupled classes. But generally classes shouldn't be tightly coupled like that. They should either be classes declared as part of an owner class, or subclasses. And since C++ does multiple inheritance, one could easily use a mix-in class to achieve the same in a much more readable fashion.