当前位置:编程学习 > C/C++ >>

编译期判断类型之间是否可以convert

[cpp]
//T could converted to U ?  
template<typename T, typename U> 
class Conversion 

private: 
    typedef char Small; 
    struct Big{ char big[2]; }; 
 
    static Small _helper_fun(U); 
    static Big _helper_fun(...); 
    static T _make_T(); 
public: 
    enum { 
        Exists = (sizeof(_helper_fun(_make_T())) == sizeof(Small)), 
        Exists2Way = ( Exists && Conversion<U,T>::Exists), 
        Same = false 
    }; 
}; 
 
// partial specialization for "same type"  
template<typename T> 
class Conversion<T, T> 

public: 
    enum{ 
    Exists = true, 
    Exists2Way = true, 
    Same = true 
    }; 
}; 
 
// T is subclass of U ?  
template<typename T, typename U> 
class IsSubclass 

public: 
    enum{ 
    Result = Conversion<T*, U*>::Exists 
    }; 
}; 

//T could converted to U ?
template<typename T, typename U>
class Conversion
{
private:
    typedef char Small;
    struct Big{ char big[2]; };

    static Small _helper_fun(U);
    static Big _helper_fun(...);
    static T _make_T();
public:
    enum {
        Exists = (sizeof(_helper_fun(_make_T())) == sizeof(Small)),
        Exists2Way = ( Exists && Conversion<U,T>::Exists),
        Same = false
    };
};

// partial specialization for "same type"
template<typename T>
class Conversion<T, T>
{
public:
    enum{
    Exists = true,
    Exists2Way = true,
    Same = true
    };
};

// T is subclass of U ?
template<typename T, typename U>
class IsSubclass
{
public:
    enum{
    Result = Conversion<T*, U*>::Exists
    };
};


 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,