在不知道成员类型的情况下如何与SFINAE进行检查? [英] How to check with SFINAE if a member exists, without knowing the member's type?
本文介绍了在不知道成员类型的情况下如何与SFINAE进行检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++ 11之前的代码中,如果我正在寻找一个其类型未知的成员变量,该如何使用SFINAE来检查该成员是否存在?
In pre-C++11 code, if I'm looking for a member variable whose type I don't know, how can I use SFINAE to check if the member exists?
推荐答案
以下是您要求的使用成员检测器习惯用法的示例:
Here's an example using Member detector idiom that you asked for:
template<typename T>
struct has_x {
typedef char(&yes)[1];
typedef char(&no)[2];
// this creates an ambiguous &Derived::x if T has got member x
struct Fallback { char x; };
struct Derived : T, Fallback { };
template<typename U, U>
struct Check;
template<typename U>
static no test(Check<char Fallback::*, &U::x>*);
template<typename U>
static yes test(...);
static const bool value = sizeof(test<Derived>(0)) == sizeof(yes);
};
#include <iostream>
struct A { private: int x; }; // works with private, too
struct B { const char x; };
struct C { void x() volatile ; };
struct D : A { };
struct E {};
struct F : A, B {}; // note that &F::x is ambiguous, but
// the test with has_x will still succeed
int main()
{
std::cout
<< has_x<A>::value // 1
<< has_x<const B>::value // 1
<< has_x<volatile C>::value // 1
<< has_x<const volatile D>::value // 1
<< has_x<E>::value // 0
<< has_x<F>::value; // 1
}
它也应该与MSVC一起使用.
It should work with MSVC, too.
这篇关于在不知道成员类型的情况下如何与SFINAE进行检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文