2015-05-28 32 views
2

我想編寫一個返回給定類型的整型(float,int,char ...)的特徵。基地是:基於特定成員是否存在專用模板

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

而且我希望它爲雙倍返還:

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

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

這是行不通的。我需要合併第一和第二的聲明類似:

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

但現在什麼,如果我的圖書館的用戶類型的名爲「MyType的」,而不是「類型」的成員?我怎樣才能使這種結構專門化如下:

struct foobar{ 
    using MyType = double; 
} 

這甚至可能嗎?其實看起來應該與SFINAE

工作

回答

2

你可以做到這一點使用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>{}; 
相關問題