gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:49:10 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com