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
}
Live test.
It should work with MSVC, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With