程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 編譯期判斷類型之間是否可以convert

編譯期判斷類型之間是否可以convert

編輯:C++入門知識

[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
    };
};


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved