用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库中就封装了一个宏。
用sizeof来实现编译时的类型辨别 — Windows Live
sizeof的实现
变态的验证码 — Windows Live
永远的胡胡 — Windows Live
培根的经典名言 — Windows Live
闲云野鹤的家 — Windows Live
人類是地球的癌細胞 — Windows Live
硅谷的工程师文化 — Windows Live
akane870 的日志 — Windows Live
徐徐渐进 的日志 — Windows Live
信用卡的利润来源 — Windows Live
直销成功的三大法宝 — Windows Live
关于菊花的诗词 — Windows Live
我们的MCM — Windows Live
写给猫咪的悼词 — Windows Live
紫霞控 — Windows Live
浪淘沙 — Windows Live
皋陶谟 — Windows Live
紫霞控 — Windows Live
盘庚下 — Windows Live
盘庚下 — Windows Live
做个好女人 — Windows Live
社会学研究课题 — Windows Live
金贞淑 — Windows Live