介绍一个雕虫小技:编译期判断类的继承性。具体来说就是类型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的父类或者T和U是相同类型
#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