c++ - 检查类是否有指针数据成员

标签 c++ boost c++11 sfinae

有没有办法测试一个类是否有指针数据成员?

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 );
}

Live example

当然,您需要知道要检查的成员变量的名称,因为 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" );
    // ...
}

Live example

请注意,我只是添加了 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/

相关文章:

c++ - 拥有自己的类模板和其他模板参数的 friend

c++ - Qt - 自定义小数点和千位分隔符

c++ - 从派生范围调用函数

c++ - C++11 对 Unicode 的支持程度如何?

c++ - 定义宏时 "##x"是什么意思

c++ - 模板类型列表中的递归取消引用,如何返回正确的类型

c++ - 自定义验证器不允许 default_value

c++ - 线程锁定互斥量比 std::conditional_variable::wait() 更快

boost - 关闭带有挂起连接的 boost::asio::ip::tcp::socket

c++ - boost 图形复制和删除顶点