Search code examples
c++templatestypestype-traits

How to conditionally define a typedef to be one of two types


I'm sure that boost has some functions for doing this, but I don't know the relevant libraries well enough. I have a template class, which is pretty basic, except for one twist where I need to define a conditional type. Here is the psuedo code for what I want

struct PlaceHolder {};

template <typename T>
class C {
    typedef (T == PlaceHolder ? void : T) usefulType;
};

How do I write that type conditional?


Solution

  • In modern C++ using the convenience templates std::conditional_t and std::is_same_v:

    using usefulType = std::conditional_t<std::is_same_v<T, PlaceHolder>, void, T>;
    

    In C++11, using only typedef and without the convenience aliases:

    typedef typename std::conditional<std::is_same<T, PlaceHolder>::value, void, T>::type
        usefulType;