Declaring a conditional link in a template class

In a template class, how to conditionally define a property template for a template?

Example:

template<class Type, unsigned int Dimensions> class SpaceVector { public: std::array<Type, Dimensions> value; Type &x = value[0]; // only if Dimensions >0 Type &y = value[1]; // only if Dimensions >1 Type &z = value[2]; // only if Dimensions >2 }; 

Is this conditional ad possible? if so, how?

+7
c ++ alias c ++ 11 templates
source share
2 answers

Specialize in the first two cases:

 template<class Type> class SpaceVector<Type, 1> { public: std::array<Type, 1> value; // Perhaps no need for the array Type &x = value[0]; }; template<class Type> class SpaceVector<Type, 2> { public: std::array<Type, 2> value; Type &x = value[0]; Type &y = value[1]; }; 

If you have a common base class, you get a certain amount of polymorphism for overall functionality.

+7
source share

If you can do without an array, you can do this:

 template<class Type, std::size_t Dimension> class SpaceVector { public: Type x; }; template<class Type> class SpaceVector<Type, 2> : public SpaceVector<Type,1> { public: Type y; }; template<class Type> class SpaceVector<Type, 3> : public SpaceVector<Type,2> { public: Type z; }; 

This is more scalable if you decide to support more than three elements, but otherwise the answer to the question about Bathsheba is probably more appropriate.

+2
source share

All Articles