Templates are both the blessing and curse of C++. Someone hates them, someone loves them. For those of you are in the latter group, whats your favorite template "hack", and what does it do?
I'll start with my personal favorite, the "friender". This template allowes access to protected members - which I very frequently use for unittesting (lets not get into a discussion about if unit tests should be used like this).
template<typename T>
class FriendIdentity {
public:
typedef T me;
};
template<class ToFriend, typename ParentClass>
class Friender: public ParentClass
{
public:
Friender() {}
virtual ~Friender() {}
private:
// MSVC != GCC
#ifdef _MSC_VER
friend ToFriend;
#else
friend class FriendIdentity<ToFriend>::me;
#endif
};
template<typename Tester, typename ParentClass>
Friender<Tester, ParentClass> &
friendMe(Tester * me, ParentClass & instance)
{
return (Friender<Tester, ParentClass> &)(instance);
}
Usage:
friendMe(this, someObject).someProtectedFunction();