Specialize template based on whether a specific member exists

北城以北 提交于 2020-01-02 10:09:11

问题


I want to write a trait that returns the integral type (float, int, char...) of a given type. Base is:

template< class T, typename T_SFINAE = void >
struct IntegralType;

template< class T >
struct IntegralType< T, std::enable_if< (std::is_integral<T>::value || std::is_floating_point<T>::value) > >{
  using type = T;
}

template< class T >
struct IntegralType<T>: IntegralType<T::type>{}

And I want it to return double for:

struct foo{
  using type = double;
}
struct bar{
  using type = foo;
}

IntegralType<double>::type == double
IntegralType<foo>::type == double
IntegralType<bar>::type == double

This does not work. I have to merge the first and 2nd declaration like that:

template< typename T, bool isIntegral = (std::is_integral<T>::value || std::is_floating_point<T>::value) >
struct IntegralType{
    using type = T;
};

template< typename T >
struct IntegralType< T, false >: IntegralType< typename T::type >{};

But what now, if a user of my library has types with members named "MyType" instead of "type"? How could I make it possible to specialize this on structs like:

struct foobar{
  using MyType = double;
}

Is this even possible? Actually looks like it should work with SFINAE


回答1:


You can do this using void_t:

//void_t for evaluating arguments, then returning void
template <typename...>
struct voider { using type = void; };
template <typename... Ts>
using void_t = typename voider<Ts...>::type;

//fallback case, no valid instantiation
template< class T, typename T_SFINAE = void >
struct IntegralType;

//enabled if T is integral or floating point
template< class T >
struct IntegralType< T, std::enable_if_t< (std::is_integral<T>::value || std::is_floating_point<T>::value) > >{
  using type = T;
};

//enabled if T has a ::type member alias
template< class T >
struct IntegralType<T, void_t<typename T::type>> : IntegralType<typename T::type>{};

//enabled if T has a ::MyType member alias
template< class T >
struct IntegralType<T, void_t<typename T::MyType>> : IntegralType<typename T::MyType>{};


来源:https://stackoverflow.com/questions/30500321/specialize-template-based-on-whether-a-specific-member-exists

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