Using enable_if to optionally add a struct member

Well: use a base class.

struct Empty {};

struct SpecialTypeCnt { SpecialType member; };

template <typename A>
struct Something: if_< /* cond */ , SpecialTypeCnt, Empty>::type {
};

Where if_ is defined as:

template <typename, typename, typename E> struct if_ { typedef E type; };

template <typename T, typename E>
struct if_<std::true_type, T, E> { typedef T type; };

(You can also specialize on a boolean)

Now of course, you need to express your condition properly.


Having said that, you should probably not use just a struct. Instead you should use a class which provides the operations that need be applied on member. Then you provide a class Null with a default behavior and a class SomeType with the behavior specific to member.

Otherwise you'll rewrite the condition everywhere you need to "perhaps" modify member, and it gets annoying real quick.


You don't need enable_if for this. Specialize your struct for special cases and leave the default implementation for the rest:

template <class A>
struct Something
{
  // your default implementation
};

template <>
struct Something<SpecialCase1>
{
  // your SpecialCase1 implementation
};

template <>
struct Something<SpecialCase2>
{
  // your SpecialCase2 implementation
};