Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional reference declaration in template class

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?

like image 437
Adrian Maire Avatar asked Feb 15 '16 09:02

Adrian Maire


2 Answers

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.

like image 180
Bathsheba Avatar answered Nov 06 '22 11:11

Bathsheba


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.

like image 40
TartanLlama Avatar answered Nov 06 '22 11:11

TartanLlama