2012-04-13 121 views
2

我正在嘗試編寫一個模板來提取boost :: shared_ptr的基類型。模板與其派生類型匹配

我寫這個模板:

template<typename T> 
struct ExtractBaseType; 

template<typename T> 
struct ExtractBaseType<boost::shared_ptr<T> > 
{ 
    typedef T type; 
}; 

它工作正常普通的shared_ptr。這:

struct A 
{ 
}; 

ExtractBaseType<boost::shared_ptr<A> >::type a_thing; 
std::cout << typeid(a_thing).name() << std::endl; 

打印「1A」。

然而,這並不編譯:

struct B : boost::shared_ptr<A> 
{ 
}; 

ExtractBaseType<B>::type b_thing; 

編譯器抱怨ExtractBaseType是不確定的。

爲什麼這麼說?這將如何完成?

+2

shared_ptr不是作爲一個基類來設計的,通常shared_ptr是按值取值的。根據您的派生類,這可能會有意想不到的行爲。 shared_ptr可能應該是一個final類,或者至少你應該像對待它一樣。 – bames53 2012-04-13 17:55:51

回答

4

這是行不通的,因爲你匹配shared_ptr沒有B。你需要匹配派生的shared_ptr

template<typename T, class = void> 
struct ExtractBaseType; 

template<class C> 
struct ExtractBaseType< 
    C, typename enable_if< 
      boost::is_base_of<shared_ptr<typename T::element_type>, T>::value 
     >::type 
    > 
{ 
    typedef typename T::element_type type; 
}; 

^沒有測試,但是其主要思想是有

好問題。這就是說,從shared_ptr繼承似乎很難看。