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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 09:36:21

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>{} );
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!