检查类是否有指针数据成员 [英] 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 )
{
}
不编译。因为Test有一个指针数据成员。
This should not compile. because Test has a pointer data member.
Test test;
foo( test )
也许我可以使用trait来禁用模板?或者是我唯一的选项宏?也许有人知道boost是否可以做到?
Maybe I can use a trait to disable the template? Or is my only option macros? Maybe someone knows if boost can do it?
推荐答案
以下可以作为保护,但成员变量必须可访问( public
),否则将无法工作:
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 );
}
当然,您需要知道会员的姓名
Of course you need to know the name of the member variable to check, as there is no general reflection mechanism built into C++.
另一种避免歧义的方法是创建a 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屋!