2012-11-27 67 views
2

我已經蒸我懷疑這下面這段代碼由基類專業類模板

struct base {}; 
struct derived : public base {}; 

template <class T> 
struct Type { }; 

template <> struct Type<base> { 
    typedef float mytype; 
}; 

typename Type<base>::mytype a=4.2; // this works 
typename Type<derived>::mytype a=4.2; // this doesnt 

任何人都可以解釋爲什麼我不能derived intantiate類模板對象,並提出一個簡單的方法來做到這一點。對於我感興趣的實際問題,有許多派生類使用它們來模擬模板類對象和/或使用typedefs。其中有太多比我想單獨專門化。

編輯:忘了提,是我不好,這就需要將C++ 03

回答

4
#include <iostream> 
#include <type_traits> 

struct base { }; 
struct derived : base { }; 

template<typename T, bool = std::is_base_of<base, T>::value> 
struct Type { }; 

template<typename T> 
struct Type<T, true> 
{ 
    typedef float mytype; 
}; 

int main() 
{ 
    Type<base>::mytype a1 = 4.2f; 
    Type<derived>::mytype a2 = 8.4f; 
    std::cout << a1 << '\n' << a2 << '\n'; 
} 

在C++ 03,std可以平凡替換boostboost::is_base_of

+0

小心C++ 11'std :: is_base_of'。 –

+0

是的,總是有[Boost.Type Traits](http://www.boost.org/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html)。只有很多人仍然堅持使用舊的C++ 11編譯器(通常是微軟的),應該提到使用C++ 11。 –

+0

@JanHudec:我正在使用gcc ... 4.3.2。 「企業」世界並沒有如此迅速地從已經驗證的技術轉向新的技術:x –

2

兩個實例具有不同模板參數的模板類是完全不相關的類類型。 Type<derived>Type<base>沒有任何關係,這當然意味着它不使用專門化並從主模板實例化。主模板沒有嵌套類型mytype