I have a templated container class that looks something like this:
template <class ItemType> class MyContainer
{
public:
[... various methods omitted for brevity...]
void Clear()
{
ItemType defaultItem;
for (int i=0; i<_numValidItems; i++) _itemArray[i] = defaultItem;
_numValidItems = 0;
}
void FastClear()
{
_numValidItems = 0;
}
private:
int _numValidItems;
ItemType * _itemArray;
};
As you can see, the Clear() method resets each item in the container to its default state, which is necessary for types where e.g. the individual items have dynamically allocated internal resources that I want the Clear() call to release.
There is also the FastClear(), which as the name implies is faster (O(1) instead of O(N)) because it simply sets _numValidItems to zero, and doesn’t actually touch any of the items in the array. This is great for POD-style ItemTypes, but not so good for e.g. file-handle types.
My question is, is there a way to use SFINAE or similar to get the compiler to decide at compile time that it is safe to make Clear() a synonym for FastClear(), i.e. when ItemType has a trivial destructor? That way the calling code wouldn’t have to remember to call FastClear() instead of Clear to get a speedup, it would work automatically.
Also, just to make things more difficult… I’d like to be able to do this without adding a dependency to Boost/TR1/C++11. (so calling is_pod() or has_trivial_destructor() aren’t good options for me)
I’d go for Boost Type Traits together with enable_if. I think it quite closely answers your question. If you don’t want the includes, you can always implement it yourself, using Boost for the inspiration. It uses SFINAE after all.