Template Typedef in C++
Arne Olav Hallingstad13th December 2008
Updated 13th December 2008
Home
Why template typedefs would be useful
I was making an N3-tree, a generalized octree where each tree node has N^3 children. If N = 2 then the N3-tree would be an Octree.
I was implementing the class as such:
template< typename T, int N = 2 > class aoN3Tree { ... }
And below the class i would like to typedef the octree version supplying some but not all template arguments. I was thinking of doing it like this:
typedef template
aoN3Tree< typename T, 2 > aoOctree;
If I'd like to make an octree I would simply write:
aoOctree< data_t > myOctree;
Perfect, but I was supprised to know this was not possible in the C++ standard. There's a bunch of places on the internet where this has been discussed and proposed as an addition to C++0x which would be great.
It is not, however, possible in general to use default arguments or typedefs to create a more usable name for a template where some, but not all, actual template arguments are fixed
The correct syntax in C++0x would be:
template< typename T > using aoOctree = aoN3Tree< T, 2 >;
Alternatively the aoOctree class can be derived from the aoN3Tree class:
template< typename T > class aoOctree : public aoN3Tree< T, 2 > {...};
This is not optimal though as a virtual destructor is required, creating a vtable wasting space. As Scott Meyers says in "Effective C++", item 7:
if a class does not contain virtual functions, that often indicates it is not meant to be used as a base class. When a class is not intended to be a base class, making the destructor virtual is usually a bad idea.
Basically a vtable adds 4 bytes on 32-bit architecture and it is no longer possible to pass an object pointer between C++ and the C counterpart unless you explicitly account for the virtual pointer.