2012-07-09 67 views
1

考慮以下幾種類型C++中是否存在錯誤類型?

template <typename T1, typename T2, typename T3> 
struct either_or 
{ 
    /* Here I need such an error type that says "Sorry, T1 is not an accepting type." */ 
    typdef error<T1> type; 
}; 
template <typename T1, typename T3> 
struct either_or <T1, T1, T3> 
{ 
    typedef T1 type; //T1 Ok 
}; 
template <typename T1, typename T2> 
struct either_or <T1, T2, T1> 
{ 
    typedef T1 type; //T1 Ok 
}; 

/* Here is function that might accept error type variable */ 

template <typename T> 
void foo(typename either_or<T, char, unsigned char>::type x) 
{ 
    /*print char or unsigned char except that T is not printable*/ 
} 

是否有C++的類型系統錯誤類型在這種情況下使用?如果沒有,我能否意識到它或如何?

+0

聽起來像你可能想'std :: enable_if' – Flexo 2012-07-09 21:06:32

+0

@Flexo嗯......我已經檢查了它以及std :: conditional和std :: is_same在C++ 11中。但是我真的需要我的函數來明確地告訴它它是什麼:-( – Yang 2012-07-09 21:10:50

回答

4

不,沒有這樣的語言或標準庫提供的類型。歡迎你來彌補自己的,如果你想:

template <typename T> 
struct error { }; 

另一種選擇是簡單地忽略基本模板的type定義。當T1,T2T3的值與兩種專業化中的任何一種不匹配時,您將獲得基本模板,該模板將不具有type成員。這會導致編譯器不考慮foo的版本,並且當您嘗試使用無效參數類型調用它時,最終會得到編譯錯誤。

+0

所以我沒有辦法讓我的函數知道這個類型是可接受的還是不正確的? – Yang 2012-07-09 21:15:51

+0

編譯器已經告訴你,如果可以接受的話,編譯器繼續編譯程序的其餘部分,如果不可接受,則表示類似於「foo」沒有接受該類型的版本。「有些編譯器會說可接受的類型是什麼,但通常在處理重載時,而不是模板,因爲重載,可能性有限,因此編譯器可以全部打印它們,使用模板很難知道所有的可能性,這是一個好的文檔比技術解決方案更容易的情況。 – 2012-07-09 21:18:33

+0

A有時候使用的技巧是導致一個更好的錯誤消息,像這樣 typedef typename T1 :: ____ THIS_TYPE_DOES_NOT_WORK type; – 2012-07-09 21:23:12

1

如何:

template <typename T1, typename T2, typename T3> 
struct either_or 
{ 
    static_assert(false, "Sorry but this doesn't work for type T1"); 
    //typdef error<T1> type; 
}; 
template <typename T1, typename T3> 
struct either_or <T1, T1, T3> 
{ 
    typedef T1 type; //T1 Ok 
}; 
template <typename T1, typename T2> 
struct either_or <T1, T2, T1> 
{ 
    typedef T1 type; //T1 Ok 
}; 

/* Here is function that might accept error type variable */ 

template <typename T> 
void foo(typename either_or<T, char, unsigned char>::type x) 
{ 
    /*print char or unsigned char except that T is not printable*/ 
} 

這應該顯示是這樣的:

error: Sorry but this doesn't work for type T1 
when instantiating either_or<T1,T2,T3> 
with T1 = <typename>, T2=<typename>, T3=<typename> 

如果編譯 - 確切的錯誤信息將取決於課程的編譯器。如果您想問 - 不,則不可能將實際類型名稱集成到消息"Sorry but this doesn't work for type T1"中 - 請參閱this線程。