Determining that a class has a specific member?

Possible duplicate:
Perhaps for a C ++ template to test the function & rsquo; existence s?

I am trying to determine if a type has a specific member. This is what I tried:

template <typename T,typename U=void>
class HasX
{
public:
    static const bool Result=false;
};

template <typename T>
class HasX<T,typename enable_if_c<(sizeof(&T::X)>0)>::type>
{
public:
    static const bool Result=true;
};


struct A
{
    int X();
};

struct B
{
    int Y();
};


int main()
{
    cout<<HasX<A>::Result<<endl; // 1
    cout<<HasX<B>::Result<<endl; // 0
}

It actually compiles and runs on GCC, but VC gives you error C2070: 'overloaded-function': illegal sizeof operandthe point of instanciation.

Is there something wrong with the code, and are there other ways to do this?

+3
source share
1 answer

Really:

typedef char (&no_tag)[1];
typedef char (&yes_tag)[2];

template < typename T, void (T::*)() > struct ptmf_helper {};
template< typename T > no_tag has_member_foo_helper(...);

template< typename T >
yes_tag has_member_foo_helper(ptmf_helper<T, &T::foo>* p);

template< typename T >
struct has_member_foo
{
    BOOST_STATIC_CONSTANT(bool
        , value = sizeof(has_member_foo_helper<T>(0)) == sizeof(yes_tag)
        );
};

struct my {};
struct her { void foo(); };

int main()
{
    BOOST_STATIC_ASSERT(!has_member_foo<my>::value);
    BOOST_STATIC_ASSERT(has_member_foo<her>::value);

    return 0;
} 

Copied from here .

Edit: Update AFAIK compatible code. Also note that you need to know the arguments of the return type of the method you are checking.

+6
source

Source: https://habr.com/ru/post/1753619/


All Articles