简体   繁体   English

检查类是否具有指针数据成员

[英]Check if a class has a pointer data member

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 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: 以下可以作为保护,但成员变量必须是可访问的( 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 实例

Of course you need to know the name of the member variable to check, as there is no general reflection mechanism built into C++. 当然,您需要知道要检查的成员变量的名称,因为C ++中没有内置的通用反射机制。


Another way which avoid the ambiguity is to create a has_pointer helper: 另一种避免歧义的方法是创建一个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 实例

Note that I simply added a static_assert as the first line to the function to get a nice, readable error message. 请注意,我只是添加了一个static_assert作为函数的第一行,以获得一个漂亮,可读的错误消息。 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 )
{
    // ...
}

I would like to know if there is a way to check for a pointer data member of which we do not know the name. 我想知道是否有办法检查我们不知道名称的指针数据成员。 I gave p as an example but the idea is that I do not know what the name will be or if there is only 1 pointer data member 我给了p作为一个例子,但我的想法是我不知道名称是什么,或者只有一个指针数据成员

I don't think you can. 我认为你不能。

You could use gcc's -Weffc++ which will warn about classes with pointer members (that don't have the minimum special members defined). 你可以使用gcc的-Weffc ++来警告带有指针成员的类(没有定义最小特殊成员)。

What I really think you're after, though, is "Does this class have value semantics" ("Do I need to deep clone this"). 然而,我真正认为你所追求的是“这个类是否具有价值语义”(“我需要深入克隆这个”)。 In C++ you have to assume this unless copying/assignment are prohibited . 在C ++中, 除非禁止复制/赋值,否则必须假设这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM