用sizeof来实现编译时的类型辨别 — Windows Live

来源:百度文库 编辑:神马文学网 时间:2024/03/29 00:45:05

用sizeof来实现编译时的类型辨别

想在编译时辨别类型是否是继承关系?看下面一段代码:/*
  Program for testing the convertibility.
*/
#include
using namespace std;//structure representing 'true' and 'false'.
typedef int small;
class big { char dummy[2];};//class Two is the child of class One
//and class Other has nothing to do with them.
class One { int dummy[2];};
class Two : public One{ int dummy[2];};
class Other { char c;};//Note: test function to test convertibility
//notice the return type and the parameter type
//using function overloading mechanism.
small Test(One);
big Test(...);//ellipse function!//flag constants. The incredible usage of sizeof operator!
//It caculate the size of the return type of the function
//during compilation!
//The return type of sizeof is size_t.
const bool isInheritance = ( sizeof(Test(Two())) == sizeof(small));
const bool isCovertable = ( sizeof(Test(Other())) == sizeof(small));int main()
{
    cout << "isInheritance: " << isInheritance << endl;
    cout << "isCovertable: " << isCovertable << endl;
}
这段代码可以检查两个类型是否存在继承关系,或者两个类型是否相等。其中的奥秘就在于:1)sizeof的运用。2)函数的重载。1)sizeof:根据C++规范,“The Operand is either an expression, which is not evaluated, or a parethesized type-id.”。也就是说,sizeof只关注最后表达式给他的结果类型是什么。那么在这里,不同的表达式返回的类型不同(small, big),就达成了判断。2)函数重载:由于允许。。。参数,在重载时,“不太符合”的参数就会导致编译器决定采用返回类型为big的函数。而继承关系的参数类型导致编译器采用small返回类型的函数。实际上,上面这段代码有改进之处。一是不应该依赖构造函数,因为也许要判断基本类型间的关系,解决的方法是用一个make()哑函数,返回要比较的类型。二是应该做一个封装,loki库中就封装了一个宏。