编译期判断类的继承性

介绍一个雕虫小技:编译期判断类的继承性。具体来说就是类型U是否继承自类型T。该技术的灵感和源头来自Andrei Alexandrescue的《Modern C++ Design》。原书中描述的此技术有一个小小的bug

源代码

template <class T , class U>

class __conversion

{

static char test(U);

static double test(...);

static T maket();

public:

enum{exists = sizeof(test(maket())) == sizeof(char) };

enum{exists2way = exists && __conversion<U,T>::exists};

enum{sametype = false};

};

template <class T>

class __conversion<T,T>

{

public:

enum{exists = 1};

enum{exists2way = 1};

enum{sametype = 1};

};

//判断T是否是U的父类或者TU是相同类型

#define SUPERSUBCLASS(T,U) (kimi_boost::__conversion<const U*,const T*>::exists &&\

!kimi_boost::__conversion<const T*,void*>::sametype)

//判断T是否是U的父类

#define SUPERSUBCLASS_STRICT(T,U) (SUPERSUBCLASS(T,U) &&\

!kimi_boost::__conversion<const T, const U>::sametype)

测试程序

class a{};

class b : public a{};

void supersub_test()

{

using std::cout;

using std::endl;

cout<<SUPERSUBCLASS(int,unsigned)<<endl;

cout<<SUPERSUBCLASS(int,int)<<endl;

cout<<SUPERSUBCLASS_STRICT(int,int)<<endl;

cout<<SUPERSUBCLASS(std::forward_iterator_tag,std::random_access_iterator_tag)<<endl<<endl;

cout<<SUPERSUBCLASS(a,a)<<endl;

cout<<SUPERSUBCLASS(a,b)<<endl;

cout<<SUPERSUBCLASS(b,b)<<endl;

cout<<SUPERSUBCLASS(b,a)<<endl<<endl;

cout<<SUPERSUBCLASS_STRICT(a,a)<<endl;

cout<<SUPERSUBCLASS_STRICT(a,b)<<endl;

cout<<SUPERSUBCLASS_STRICT(b,b)<<endl;

cout<<SUPERSUBCLASS_STRICT(b,a)<<endl;

}

程序结果

0

1

0

1

1

1

1

0

0

1

0

0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值