2016-08-04 49 views
1

枚舉類型假設我有這樣的代碼:獲得來自枚舉

#include <cstdio> 

enum Foo { Foo_A, Foo_B }; 
enum Bar { Bar_A, Bar_B }; 

template<typename enumeration, int enumerator> 
struct tpl; 

template<int enumerator> 
struct tpl<Foo, enumerator> 
{ 
    tpl() { printf("Foo: %d\n", enumerator); } 
}; 

template<int enumerator> 
struct tpl<Bar, enumerator> 
{ 
    tpl() { printf("Bar: %d\n", enumerator); } 
}; 

int main() 
{ 
    tpl<Foo, Foo_A> foo_a; 
    tpl<Foo, Foo_B> foo_b; 
    tpl<Bar, Bar_A> bar_a; 
    tpl<Bar, Bar_B> bar_b; 
    return 0; 
}; 

有沒有減少「重複」在使用場所的方法嗎?即我不能從枚舉數「Foo_A」中推導枚舉類型「Foo」,並在上面的模板代碼中使用它?一個枚舉類會在這裏幫助嗎?

+2

這段代碼看起來像解決了一些問題。問題是什麼? –

回答

2

您的問題的答案是,目前還沒有辦法做到這一點。你所面對的是所謂的template <typename T, T t>成語。事實上,如果你使用谷歌,你會發現近75,000個點擊,並且沒有解決方法。你必須像你一樣專業化。


但是地平線上有好消息。這已經提出了標準委員會多次在過去的十年:

  • N3405提出template <typename T t>津貼哪裏T是類型和t是值,只有一個值作爲模板參數傳遞
  • N3601提出template <typename T, T t>是一個特殊的情況下,編譯器將只接受一個值作爲模板參數,並從該會推斷Tt
  • N4469建議關鍵字auto是llowed到指定元參數:template <auto t>使得值可以作爲模板參數t獲得通過,它的類型推斷

5月4列涅薩`15次會議上,N4469終於獲得牽引力賺取的鼓勵和對請求在標準委員會會議上修改:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4539.html#9

第一次修訂P0127R0於2015年9月25日提交。

後續修訂於16年3月4日提交:P0127R1提出對概念工作草案部分的編輯。

P0127R2專注於完全指定工作草案的非概念部分中的習語變化,因爲目前還不清楚概念是否將包含在C++ 17中。該版本被接納進入C++ 17個標準06月23 '16:http://developerblog.redhat.com/2016/07/13/red-hat-iso-c-standards-meeting-june-2016-core-language/

所以用C++ 17的到來,你將能夠處置template <typename T, T t>成語和使用:

template <auto t> 
struct tpl{ 
    tpl(){ cout << typeid(decltype(t)).name() << ": " << t << endl; } 
}; 
+1

如果有人很好奇,Visual Studio使用'type_info :: raw_name()'輸出重名的名字,這與'type_info :: name()'的名字GCC輸出類似。 –

+0

這是否意味着模板類型可能超載,'f ()'調用另一個函數'f ()'? –

+1

@JimV你正在談論的是專業化(現在這是可能的)。這個問題是關於'template '成語的。其中我必須調用'tpl '即使'13'顯然是一個'int'。 N4469試圖允許我們調用'tpl <13>'並且能夠將*用作* *類型*和*值模板參數。 –