This example presents another useful building block for meta-programming: static if. Using template specialization, similar to static assert example, we can select one of 2 types at compile time. The condition is defined following way:

template<bool cond, typename T1, typename T2>
struct static_if {
   typedef T1 type;

template<typename T1, typename T2>
struct static_if<false, T1, T2> {
   typedef T2 type;

This "template function" returns a type, and can be used to select a type depending on some compile-time condition.

template<typename T, typename U>
class Buffer {
      typename static_if<sizeof(T) >= sizeof(U), T, U>::type

   char buf[sizeof(BiggestType)];

The class in example above allocates a buffer big enough to contain any of template types T and U, by selecting the largest type with "static_if".

Please also note the use of typename keyword inside the class - we must let compiler know that type is actually a type (and not, for example, constant value of name of a function).

Last edited Nov 29, 2007 at 7:09 PM by migo, version 1


No comments yet.