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(); //稻草人函数
public:
enum { exists = sizeof(Test(MakeT())) == sizeof(Small)};
};
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
cout<< Conversion<double,int>::exists << ' ';
getchar();
return 0;
}
sizeof 并不会真有任何表达式被求值。
====================================
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();
public:
enum { exists = sizeof(Test(MakeT())) == sizeof(Small)};
enum { exists2way = exists &&
Conversion<U,T>::exists };
enum { sameType = false};
};
template <class T>
class Conversion<T,T>
{
public:
enum { exists = 1; exists2way =1; sameType = false};
};
class A
{
int a;
};
class B :public A
{
int a;
};
#define SUPERSUBCLASS(T,U)
(Conversion<const U*,const T*>::exists &&
!Conversion<const T*,void *>::sameType)
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
cout<< Conversion<double,int>::exists << ' ';
if( SUPERSUBCLASS(A,B) )
{
cout<< "SUPERSUBCLASS<A,B>,A is base class" << ' ';
}
getchar();
return 0;
}