2012-05-10 52 views
1

有這樣的代碼:局部模板模板專業化

template<typename T, template<typename, typename> class OuterCont, template<typename, typename> class InnerCont, class Alloc=std::allocator<T>> 
class ContProxy { 
    OuterCont<T, InnerCont<T, Alloc>> _container; 
}; 
typedef ContProxy<int, std::vector, std::list> IntCont; 

但是需要在某些情況下使用T*代替std::list<T>InnerCont - 這樣的:

template<typename T, template<typename, typename> class OuterCont, T*, class Alloc=std::allocator<T>> 
class ContProxy { 
    OuterCont<T, T*> _container; 
}; 

是否有可能使用的偏特這種情況下的'模板模板'參數?
或如何以最小的頭痛將其歸檔。

回答

3

類型上簡單模板通常更容易。你無法真正捕捉到模板模板的每一種情況 - 如果有人想使用具有六個模板參數的容器怎麼辦?因此,嘗試這樣的事情:

template <typename T, typename C> 
struct ContProxy 
{ 
    typedef C     container_type; 
    typedef typename C::second_type second_type; 

    container_type container_; 
}; 

ContProxy<int, MyContainer<int, std::list<int>> p; 
0

我也將與kerrek的解決方案去,但除此之外,我能想出的最好的事情是這樣的。

問題是,InnerCont在基本模板中被聲明爲模板類型,所以您不能將它專門化爲原始指針。所以你可以創建一個代表指針的虛擬模板並使用它。

template<typename,typename> class PtrInnerCont; //just a dummy template that does nothing 

template<typename T, template<typename, typename> class OuterCont, template<typename, typename> class InnerCont, class Alloc=std::allocator<T>> 
class ContProxy { 
    OuterCont<T, PtrInnerCont<T, Alloc>> _container; 
}; 
typedef ContProxy<int, std::vector, std::list> IntCont; 

template<typename T, template<typename, typename> class OuterCont, class Alloc> 
class ContProxy<T, OuterCont, PtrInnerCont, Alloc> { 
    OuterCont<T, T*> _container; 
}; 

typedef ContProxy<int, std::vector, PtrInnerCont> MyCont; 
0

你真的不能真正做你現在正在做的事情。不是以標準的方式。 C++容器不採用相同的模板參數。

做類似這樣:

template< typename T, 
      template<typename, typename> class OuterCont, 
      template<typename, typename> class InnerCont, 
      class Alloc=std::allocator<T>> 
class ContProxy { 
    typename OuterCont<T, typename InnerCont<T, Alloc>::type>::type _container; 
}; 

然後你就可以像這樣創建不同的容器發電機:

template < typename T, typename A = std::allocator<T> > 
struct vector_gen { typedef std::vector<T,A> type; }; 

或者您的指針之一:

template < typename T, typename Ignored > 
struct pointer_gen { typedef T* type; };