7

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Might also want a static_assert in the primary template to ensure that Dimensions is valid.
Nice, however, why not have the specializations derive from each other?
@songyuanyao: changed it, although the way I had it compiled (perhaps in error) in MSVC2013.
What about making the reverse specialization? deleting the reference if dimension is less than k?
@TartanLlama Thanks, but I don't see why not (it's very possible I'm not following your logic through). Perhaps I'll try it for myself and see further.
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.