讀loki有感,編譯階段發現兩個類能否轉化

來源:互聯網
上載者:User

 

開發環境:VS2005(VC8)
以下代碼在VS2002上運行不了,據說VS2002(VC7)不完全支援偏特化,VS2003(VC7.1)就支援了。

問題提出:
一,已知類型T,U,在編譯階段如何知道T能否轉化成U。
template <class T, class U>
struct ConversionHelper
{
 static long   Test(...);//WQ註:C++中,不定參數已不需要“至少一個定參”了。
 static short Test(U);
 static T MakeT();
};

template <class T, class U>
struct Conversion
{
 typedef ConversionHelper<T, U> H;
 enum { exists = sizeof(short) == sizeof(H::Test(H::MakeT())) };
};


class A
{
public:
 A()
 {
  TRACE("\r\nAr\n");
 }

};
class  B : public A
{
public:
 B()
 {
  TRACE("\r\nBr\r\n");
 }
};
測試代碼:
bool b1 = Conversion<B,A>::exists;
bool b2 = Conversion<A,B>::exists;
運行結果分別為true,false.

二,接上面的問題。如果T能轉化成U,則定義一個U類型的對象,否則定義T類型的變數。
 template <int flag, typename T, typename U>
 struct Select  
 {
  typedef U Result;

 }; 

 template <typename T, typename U>
 struct Select<0, T, U>
 {
  typedef T Result;
 };
測試代碼:
Select<Conversion<B,A>::exists,B,A>::Result type;
type的類型是A;B不再繼承與A,則type類型是B。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.