[C ++] Boost is_base_of implementation

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 () is a type conversion operator, which converts a class type value into another type value. The reserved word operator is followed by the target type of the conversion. Refer to the type coercion member function for details.

When Base is not a superclass of Derived, operator Devied () and operator Base () const are not overloaded; next, both function type conversion functions can match helper (Conv (), 0), because operator Devied () satisfies static char helper (Devied, T); operator Base () const satisfies static int helper (Base, int); but due to the rule of preferentially matching non-template functions, static int helper (Base, int will be matched here ); Conv () will be converted to Base, the type returned by helper (Conv (), 0) is int, and finally sizeof (int)! = 1.

When Base is a superclass of Devied, the operator Devied () and operator Base () const are overloaded. Because Conv () is not a const type, call operator Devied () to do type conversion, and finally only match static char helper (Devied, T); the returned type is char, and finally sizeof (char) == 1.

Published 401 original articles · Liked 14 · Visits 100,000+

Guess you like

Origin blog.csdn.net/LU_ZHAO/article/details/105446499