问题
Let's say I have several container classes like these:
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 */
};
And I have a class which accepts one of these as a template parameter:
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)
};
My question is, can I somehow (probably through tricky template parameter magic) make the consuming class accept any type of container (fixed or variable-sized, even with differing template signatures)?
The only guarantees about the template signatures are, if it is a Fixed-sized container it will have 2 parameters <Type, Size> and one if it is a Variable-sized container <Type>
回答1:
It's way less tricky than you think it is. You can just template on the container itself:
template <class Container>
class Polygon {
Container vertices;
};
This will work for anything that meets your container requirements, be it fixed sized or not.
The problem of choosing the right template arguments for the container gets moved to instantiation point where the parameters and types must be known anyways.
来源:https://stackoverflow.com/questions/38702816/templated-fixed-variable-sized-class