Check if a class has a pointer data member

2019-02-20 13:43发布

问题:

Is there a way to test if a class has a pointer data member?

class Test
{
  int* p;
}

template< typename T >
foo( T bla )
{
}

This should not compile. because Test has a pointer data member.

Test test;
foo( test )

Maybe I can use a trait to disable the template? Or is my only option macros? Maybe someone knows if boost can do it?

回答1:

The following can work as a protection, but the member variable has to be accessible (public), otherwise it won't work:

#include <type_traits>

class Test
{
public:
  int* p;
};

template< typename T >
typename std::enable_if< std::is_pointer< decltype( T::p ) >::value >::type
foo( T bla ) { static_assert( sizeof( T ) == 0, "T::p is a pointer" ); }

template< typename T >
void foo( T bla )
{
}

int main()
{
    Test test;
    foo( test );
}

Live example

Of course you need to know the name of the member variable to check, as there is no general reflection mechanism built into C++.


Another way which avoid the ambiguity is to create a has_pointer helper:

template< typename, typename = void >
struct has_pointer : std::false_type {};

template< typename T >
struct has_pointer< T, typename std::enable_if<
                         std::is_pointer< decltype( T::p ) >::value
                       >::type > : std::true_type {};

template< typename T >
void foo( T bla )
{
    static_assert( !has_pointer< T >::value, "T::p is a pointer" );
    // ...
}

Live example

Note that I simply added a static_assert as the first line to the function to get a nice, readable error message. You could, of course, also disable the function itself with something like this:

template< typename T >
typename std::enable_if< !has_pointer< T >::value >::type
foo( T bla )
{
    // ...
}


回答2:

I would like to know if there is a way to check for a pointer data member of which we do not know the name. I gave p as an example but the idea is that I do not know what the name will be or if there is only 1 pointer data member

I don't think you can.

You could use gcc's -Weffc++ which will warn about classes with pointer members (that don't have the minimum special members defined).

What I really think you're after, though, is "Does this class have value semantics" ("Do I need to deep clone this"). In C++ you have to assume this unless copying/assignment are prohibited.