【C++】Boost之is_base_of实现

template<typename Based,typename Derived,bool = (is_class<Based>::value && is_class<Derived>::value)>
class is_base_of
{
    template<typename T>
    static char helper(Derived, T) {};
    static int helper(Based, int) {};
    struct Conv
    {
        operator Derived();
        operator Based() const;
    };

public:
    static const bool value = sizeof(helper(Conv(),0)) == 1;
};

template<typename Based,typename Derived>
class is_base_of<Based,Derived,false>
{
public:
    static const bool value = is_same<Based, Derived>::value;
};

operator Devied() 是类型转换操作符,将类类型值转变为其他类型值的转换,在保留字 operator 之后跟着转换的目标类型,详细参考类型强制转换成员函数。

当 Base 不是Derived 的超类时,那 operator Devied() 和 operator Base() const 则不是重载关系了;接下来,两个函数类型转换函数都可以匹配 helper(Conv(), 0) ,因为 operator Devied() 满足 static char helper(Devied, T); operator Base() const 满足 static int helper(Base, int);但是由于优先匹配非模板的函数的规则,在这里会匹配 static int helper(Base, int);Conv()会转换成Base,helper(Conv(), 0)返回的类型是int,最后 sizeof(int) != 1 。

当 Base 是Devied 的超类时,那 operator Devied() 和 operator Base() const 则是重载 关系。那由于 Conv() 不是const类型,调用 operator Devied() 做类型转换,最后只能匹配 static char helper(Devied, T); 返回的类型是char,最后 sizeof(char) == 1 。

发布了401 篇原创文章 · 获赞 14 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/LU_ZHAO/article/details/105446499