I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.
I'm only using the friend-keyword to unittest protected functions. Some will say that you shouldn't test protected functionality. I, however, find this very useful tool when adding new functionality.
However, I don't use the keyword in directly in the class declarations, instead I use a nifty template-hack to achive this:
template
class FriendIdentity {
public:
typedef T me;
};
/**
* A class to get access to protected stuff in unittests. Don't use
* directly, use friendMe() instead.
*/
template
class Friender: public ParentClass
{
public:
Friender() {}
virtual ~Friender() {}
private:
// MSVC != GCC
#ifdef _MSC_VER
friend ToFriend;
#else
friend class FriendIdentity::me;
#endif
};
/**
* Gives access to protected variables/functions in unittests.
* Usage: friendMe(this, someprotectedobject).someProtectedMethod();
*/
template
Friender &
friendMe(Tester * me, ParentClass & instance)
{
return (Friender &)(instance);
}
This enables me to do the following:
friendMe(this, someClassInstance).someProtectedFunction();
Works on GCC and MSVC atleast.