先上马
#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
为什么可以这么用
- 利用了函数重载
- 利用了ellipsis match策略, 该策略比automatic conversion优先级还要低
- sizeof不会去求它的参数值(意味着, 函数不会被调用, 甚至不会实例化)