有没有办法测试一个类是否有指针数据成员?
class Test
{
int* p;
}
template< typename T >
foo( T bla )
{
}
这不应该编译。因为 Test 有一个指针数据成员。
Test test;
foo( test )
也许我可以使用特征来禁用模板?或者是我唯一的选择宏?也许有人知道 boost 是否可以做到这一点?
最佳答案
以下内容可以作为保护,但成员变量必须可访问(public
),否则将不起作用:
#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 );
}
当然,您需要知道要检查的成员变量的名称,因为 C++ 中没有内置通用的反射机制。
避免歧义的另一种方法是创建一个 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" );
// ...
}
请注意,我只是添加了 static_assert
作为函数的第一行,以获得漂亮、可读的错误消息。当然,您也可以通过以下方式禁用该功能本身:
template< typename T >
typename std::enable_if< !has_pointer< T >::value >::type
foo( T bla )
{
// ...
}
关于c++ - 检查类是否有指针数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21498421/