Detecting Convertibility and Inheritance at Compile Time

先上马

#include <iostream>

template<class T, class U>
class Conversion
{
    typedef char Small;
    class Big { char dummy[2]; };
    static Small Test(U);
    static Big Test(...);
    static T MakeT();  // 防止T的构造函数是private, 因此使用MakeT()
public:
    enum { exists = sizeof(Test(MakeT())) == sizeof(Small),
           sameType = false };
};

template <class T>
class Conversion<T, T>
{
public:
    enum { exists = 1, sameType = 1 };
};

#define SUPERSUBCLASS(T, U) \
    (Conversion<const U*, const T*>::exists && \
     !Conversion<const T*, const void*>::sameType)

#define SUPERSUBCLASS_STRICT(T, U) \
    (SUPERSUBCLASS(T, U) && \
     !Conversion<const T, const U>::sameType)

class A
{

};

class B : public A
{

};

int main(int argc, char* argv[])
{
	using namespace std;
    cout << SUPERSUBCLASS(A, B) << endl;
    cout << SUPERSUBCLASS(B, A) << endl;

    return 0;
}

输出:

1
0

为什么可以这么用

  1. 利用了函数重载
  2. 利用了ellipsis match策略, 该策略比automatic conversion优先级还要低
  3. sizeof不会去求它的参数值(意味着, 函数不会被调用, 甚至不会实例化)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值