[英]Partial template template specialization
有這個代碼:
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;
};
在這種情況下,是否可以使用'模板模板'參數的部分特化?
或者如何以最小的麻煩歸檔它..
簡單地在類型上模板通常更容易。 您無法使用模板模板捕獲每種情況 - 如果有人想要使用具有六個模板參數的容器,該怎么辦? 所以嘗試這樣的事情:
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;
我也會采用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;
你實際上不能真正做你正在做的事情。 不是以標准的方式。 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; };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.