2016-08-01 25 views
0

比方說,我有幾個容器類這樣的:爲模板固定+可變大小的類

template<typename T> class Container 
{ 
    /* ... */ 
}; 

template<typename T, size_t> class Array : public Container<T> 
{ 
    /* Fixed-sized Container */ 
}; 

template<typename T> class Vector : public Container<T> 
{ 
    /* Variable-sized Container */ 
}; 

而且我有接受其中的一個作爲模板參數類:

template<typename T, template<typename> class U, size_t M> class Polygon 
{ 
    U<T> Vertices; // Problem, what if user passes Array (it needs 2 parameters) 
    U<T, M> Vertices; // Problem, what if the user wants to use a variable-sized container (it needs only 1 parameter) 
}; 

我問題是,我可以以某種方式(可能通過棘手的模板參數魔術)使消費類接受任何類型的容器(固定或可變大小,即使具有不同的模板簽名)?

有關模板簽名的唯一保證是,如果它是一個固定大小的容器中,將有2個參數<Type, Size>和一個,如果它是一個變量大小容器<Type>

回答

3

它的方式少棘手比你想象它是。你可以只模板容器本身上:

template <class Container> 
class Polygon { 
    Container vertices; 
}; 

這將爲任何符合您要求的容器的工作,無論是固定大小與否。

爲容器選擇正確的模板參數的問題被移至實例化點,其中必須知道參數和類型。