2014-09-21 183 views
1

我有一個模板化結構,它使用模板專業化(從https://www.justsoftwaresolutions.co.uk/articles/exprtype.pdf獲取)將ID映射到類型。評估模板(模板模板參數)的C++模板參數

template<int id> 
struct IdToType 
{}; 
template<> 
struct IdToType<1> 
{ 
typedef bool Type; 
}; 
template<> 
struct IdToType<2> 
{ 
typedef char Type; 
}; 

現在我想調用這樣 的getValue()

的函數,其中該函數的返回值是ID的相應類型。

template</*.... I don't know what to put here...*/ T> 
idToType<T>::Type getValue() // I don't know exactly how to define the return value 
{ 
    // whant to do some things with the provided ID and with the type of the id 
} 

因此,在短期: - 我想用模板的功能,我可以用一個ID爲模板參數。 - 該函數需要將與ID對應的類型作爲返回值(我從IdToType :: Type中獲取相應的類型)。 - 在函數的主體中,我想訪問ID和ID的類型。 - 我認爲這應該可以使用模板模板參數。但我不確定這一點。

我希望這是多麼清晰......

在此先感謝!

回答

4
template <int id> 
typename IdToType<id>::Type getValue() 
{ 
    using T = typename IdToType<id>::Type; 
    return 65; 
} 

DEMO

+0

謝謝!這有助於...... – woodtluk 2014-09-21 19:58:32

1

該代碼給出警告變量 'VAL' 未被使用。但是由於我們不想用getValue()中的類型來做什麼,所以我以這種方式離開了代碼。

char getValueImpl(char) 
{ 
    return 'c'; 
} 


bool getValueImpl(bool) 
{ 
    return true; 
} 

template<int X> 
typename IdToType<X>::Type getValue() 
{ 
    typename IdToType<X>::Type val; 
    return getValueImpl(val); 

} 


int main() 
{ 

    std::cout << getValue<2>() << "\n"; 
    std::cout << getValue<1>() << "\n"; 

}