检查一类具有指针数据成员 [英] Check if a class has a pointer data member

查看:125
本文介绍了检查一类具有指针数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来测试,如果一个类有一个指针数据成员?

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?

推荐答案

以下可以作为保护工作,但成员变量必须是可访问的(公共),否则它不会工作:

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

活生生的例子

当然,你需要知道的成员变量来检查的名称,因为没有内置到C ++没有一般的反射机制。

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

这避免了歧义的另一种方法是创建一个 has_​​pointer 助手:

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

活生生的例子

请注意,我只是增加了一个 static_assert 作为第一线的功能得到一个不错的,可读的错误信息。你可以,当然,也禁用该功能本身是这样的:

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

这篇关于检查一类具有指针数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆