2016-08-01 43 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; 
}; 

这将为任何符合您要求的容器的工作,无论是固定大小与否。

为容器选择正确的模板参数的问题被移至实例化点,其中必须知道参数和类型。