Check if the class has a pointer data item

Is there a way to check if a class has a pointer data element?

class Test { int* p; } template< typename T > foo( T bla ) { } 

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

 Test test; foo( test ) 

Maybe I can use the tag to disable the template? Or is my only macro option? Maybe someone knows if boost can do this?

+1
c ++ boost c ++ 11 sfinae
source share
2 answers

The following actions may work as protection, but the member variable must be accessible ( public ), otherwise it will not 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 ); } 

Living example

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


Another way to avoid ambiguity is to create a has_pointer :

 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" ); // ... } 

Living example

Note that I just added static_assert as the first line of the function to get a nice, readable error message. Of course, you can also disable this feature, for example:

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

I would like to know if there is a way to check the data element of a pointer whose name we do not know. I gave p as an example, but the idea is that I don’t know what this name will look like, or if there is only one pointer data element

I do not think you can.

You can use gcc -WeffC ++, which will warn about classes with pointer elements (which do not have specific minimum special members).

What I really think you need is "Does this class have semantics of meanings" ("I need to deeply clone this"). In C ++, you should assume this if copy / assignment is forbidden .

+1
source share

All Articles