2014-11-06 44 views
0

我具有以下的模板:C++型性狀來提取模板參數的專業化值

template<typename T, const char *name_ > 
struct named { 
    typedef T type; 
    static constexpr const char *name = name_; 
}; 

我想有型性狀其中:

  • 將提取的類型和名稱(2不同)如果參數類型爲「named」
  • 如果參數不同,則會提取原始類型和空字符串 類型。

例子:

template<typename T> 
void foo() { 
    typename cppdi::extract_type<T>::type x; 

    std::cout << "type: " << typeid(x).name() << 
       ", name: " << cppdi::extract_name<T>::value << std::endl; 
} 

char bar[] = "bar"; 

void test() { 
    foo<int>();    // type: i, name: 
    foo<named<int, bar>>(); // type: i, name: bar 
} 

是否有可能實現這樣的extract_typeextract_name

+0

它有助於發佈編譯代碼片段。我將編輯它們以減少破壞,如果它們不符合您的想法,請隨時恢復。 – Yakk 2014-11-06 19:10:14

+0

在檢查Daniel的答案後自己編輯:) – Daimon 2014-11-06 19:37:58

+0

@Daimon我想我剛剛意識到「missing」typedef混淆的內容是:只將'typeid()'應用於表達式(變量),而變量本身在你的代碼中是多餘的。它也解釋了你爲什麼要求'extract_type <...> :: value'而不是'extract_type :: type'。你知道你也可以將'typeid()'直接應用於*類型*?這就是我在答案中的實例中所做的,另請參見http://cppreference.com/ – 2014-11-06 20:41:20

回答

6

寫您的特點是這樣的:

template< typename T > 
struct extract_type 
{ using type = T; }; 

template< typename T, const char* S > 
struct extract_type< named< T, S > > 
{ using type = T; }; 

template< typename T > 
struct extract_name 
{ static constexpr const char* value = ""; }; 

template< typename T, const char* S > 
struct extract_name< named< T, S > > 
{ static constexpr const char* value = S; }; 

這還不行,你給的代碼是非法的幾個地方。我在這live example中修正了它們。

+0

我不得不閱讀你的答案來理解這個問題,但推測問題的解決方案是偉大的;-) – Oguk 2014-11-06 19:11:39

+0

Thx,不得不修改原始問題一點,但你的特點工作很好 – Daimon 2014-11-06 19:42:36