5

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?

2
  • Interesting. Under what circumstance would this be useful? Can you provide an example. Commented Jun 9, 2010 at 17:53
  • Here was my example. For one the template arguments, say TYPE, having value PlaceHolder means "turn off some feature". There are a set of callbacks that have return type TYPE* that the natural meaning of turning off the feature is for the callbacks to have return type void. usefulType is the return value for the callbacks. Commented Jun 9, 2010 at 19:18

3 Answers 3

10

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; 
Sign up to request clarification or add additional context in comments.

Comments

6

I think this is the principle you're after:

template< class T > struct DefineMyTpe { typedef T usefulType; }; template<> struct DefineMyType< PlaceHolder > { typedef void usefulType; }; template< class T > class C { typedef typename DefineMyType< T >::usefulType usefulType; }; 

Comments

2
template < typename T > struct my_mfun : boost::mpl::if_ < boost::is_same<T,PlaceHolder> , void , T > {}; template < typename T > struct C { typedef typename my_mfun<T>::type usefulType; }; 

1 Comment

Code should be prefixed by 4 spaces. You can select text and click the 101010 button to do it in bulk.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.