Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check with SFINAE if a member exists, without knowing the member's type?

Tags:

c++

sfinae

member

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?

like image 273
user541686 Avatar asked Oct 02 '22 01:10

user541686


1 Answers

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.

like image 69
jrok Avatar answered Oct 03 '22 15:10

jrok