In a template class, how to define a property alias conditionally to the 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 declaration possible? if yes, how?
Specialise 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 then you gain a measured amount of polymorphism for common functionality.
If you can do without the array, you could 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, Bathsheba's answer is probably more suitable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With