M.M
M.M

Reputation: 141598

How to specialize a template function for enum, and specific type?

I currently have a function:

template<typename T> 
bool func(T &t, int x)
{
    // do stuff...
}

However I would like to have three different function bodies:

  1. T being an enum
  2. T being unsigned char
  3. Everything else

I have tried this already but didn't get far.

What are the correct function declarations for these three cases to work?


The closest I have been able to come up with is Case 1 being:

template<typename T>
typename std::enable_if< std::is_enum<T>::value, bool >::type func( T &t, int x)

and Case 3 being:

template<typename T>
typename std::enable_if< not std::is_enum<T>::value, bool >::type func( T &t, int x)

however I have not been able to make something work for Case 2 that compiles. As a workaround I have an if statement inside Case 3 to handle unsigned chars but that is not ideal.

Upvotes: 3

Views: 1749

Answers (2)

Jarod42
Jarod42

Reputation: 217293

Turn out the comment about overload into answer:

// For enum
template<typename T>
typename std::enable_if<std::is_enum<T>::value, bool>::type
func(T& t, int x);

// for unsigned char
bool func(unsigned char& t, int x);

// for other
template<typename T>
typename std::enable_if<!std::is_enum<T>::value, bool>::type
func(T& t, int x);

Live example

An alternative is to use specialization for unsigned char:

// for other
template<typename T>
typename std::enable_if<!std::is_enum<T>::value, bool>::type
func(T& t, int x);

// specialization for unsigned char
template <>
bool func(unsigned char& t, int x);

Live example

Upvotes: 2

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

Use tag dispatching:

namespace details {
  template<class T>
  bool func( T& t, int x, std::true_type /* is_enum */, std::false_type ) {
  }
  template<class T>
  bool func( T& t, int x, std::false_type, std::true_type /* unsigned char */ ) {
  }
  template<class T>
  bool func( T& t, int x, std::false_type, std::false_type ) {
    // neither
  }
}
template<class T>
bool func( T& t, int x ) {
  return details::func( t, x, std::is_enum<T>{}, std::is_same<unsigned char, T>{} );
}

Upvotes: 9

Related Questions