如何检查SFINAE是否存在静态常量成员
How to check presence of static const member with SFINAE
>假设我有几个带有可选字段的结构:
struct Param1
{
static const bool x = true;
};
struct Param2
{
};
并想编写模板函数
template <class ParamType>
bool ReturnParam();
如果存在静态字段x
,则应返回ParamType::x
,否则应返回false
我想一些SFINAE魔法应该会有所帮助。
约束
我使用的是 MSVC 2010,因此无法使用C++11 功能中的大多数。
这段代码完美运行:
template<typename T, typename MemberPtrGetter>
struct has_member_impl
{
private:
template<typename U> static char Test(typename MemberPtrGetter::template type<U>*);
template<typename U> static int Test(...);
public:
static const bool value = sizeof(Test<T>(0)) == sizeof(char);
};
template <typename T, typename MemberPtrGetter>
struct has_member: public std::integral_constant<bool, has_member_impl<T, MemberPtrGetter>::value>
{
};
struct StaticMemberGetter
{
template <typename T, const bool = T::x>
struct type
{
};
};
struct Param1
{
static const bool x = true;
};
struct Param2
{
};
template <typename Param, typename T = void>
struct ExtractParam
{
static const bool x = false;
};
template <typename Param>
struct ExtractParam<Param, std::true_type>
{
static const bool x = Param::x;
};
template <typename Param>
bool ReturnParam()
{
return ExtractParam<Param, has_member<Param, StaticMemberGetter>>::x;
}
我使用以下特征:
#define DEFINE_HAS_SIGNATURE(traitsName, funcName, signature)
template <typename U>
class traitsName
{
private:
template<typename T, T> struct helper;
template<typename T>
static char check(helper<signature, &funcName>*);
template<typename T> static int check(...);
public:
enum { value = sizeof(check<U>(0)) == sizeof(char)};
}
DEFINE_HAS_SIGNATURE(has_x, T::x, const bool *);
然后是 SFINAE 或标签调度:
template <typename T>
typename std::enable_if<has_x<T>::value, bool>::type
ReturnParam()
{
return T::x;
}
template <typename T>
typename std::enable_if<!has_x<T>::value, bool>::type
ReturnParam()
{
return false;
}
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 地图计数确实很重要,或者只是检查是否存在
- C++中是否存在 std::conditional 的懒惰等价物?
- 无论如何,我可以确定构造函数是否存在吗?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 模板化检查是否存在带有参数列表的类成员函数?
- 是否存在包含负号的isdigit函数(过载)
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 检查编译时是否存在静态函数
- 向量是否存在行主要形式?
- 检查 TinyXML 中的元素是否存在
- 检测是否存在具有 C++17 的类成员
- 虚拟继承中是否存在多重继承?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符