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