I've come across to an Alexandrescu tutorial about traits and I have some reflections to share. This is the code:
// Example 6: Reference counting traits
//
template <class T>
class RefCountingTraits
{
static void Refer(T* p)
{
p->IncRef(); // assume RefCounted interface
}
static void Unrefer(T* p)
{
p->DecRef(); // assume RefCounted interface
}
};
template <>
class RefCountingTraits<Widget>
{
static void Refer(Widget* p)
{
p->AddReference(); // use Widget interface
}
static void Unrefer(Widget* p)
{
// use Widget interface
if (p->RemoveReference() == 0)
delete p;
}
};
How much overhead we have in this case compared to a standard virtual function member case? we are not accessing directly to the object also in this case: we are still passing a pointer. Is the compiler able to optimize it in same way?