[英]Specialize template based on whether a specific member exists
我想寫一個特征,該特征返回給定類型的整數類型(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”而不是“ type”,該怎么辦? 我如何才能專門針對以下結構:
struct foobar{
using MyType = double;
}
這有可能嗎? 實際上看起來應該與SFINAE一起使用
您可以使用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>{};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.