gpt4 book ai didi

c++ - 根据特定成员是否存在专门化模板

转载 作者:搜寻专家 更新时间:2023-10-31 01:39:53 29 4
gpt4 key购买 nike

我想编写一个返回给定类型的整数类型(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>{};

关于c++ - 根据特定成员是否存在专门化模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30500321/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com