Home > Software engineering >  How can I enable/disable a function depending on the size of an array?
How can I enable/disable a function depending on the size of an array?

Time:01-15

I'm still rather new to TMP so forgive me if this is a poorly worded question.

I'm trying to make a very generic mathematical Vector class to store any number of components, but defaults to 3 and using float as it's base representation. So if you default construct one of these vectors it will hold (0.0f,0.0f,0.0f)

The values themselves are stored in a std::array and I would like to create accessor function for ease of use. I currently have this:

std::array<Type,SIZE> e;
Type x() const {return e.at(0);};
Type y() const {return e.at(1);};
Type z() const {return e.at(2);};

What I am trying to do now is also have one for the 4th component, w but only enable it if the size of this array is >= 4. so something like this:

template<class Type, std::enable_if<.......>>
Type w() const {return e.at(3);};

This is just a vague idea of what I think it should look like. I'm aware concept exists, but I'm also struggling to write one for this situation.

CodePudding user response:

With concepts you can simply do

Type w() const requires (SIZE >= 4) {return e.at(3);};

CodePudding user response:

Prior to C 20 concepts, you can do this:

template<typename Type = float, size_t SIZE = 3>
class Vector {
    std::array<Type, SIZE> e;
public:
    template<typename Dummy = void, std::enable_if_t<SIZE >= 1, Dummy>* = nullptr>
    Type x() const { return e[0]; };

    template<typename Dummy = void, std::enable_if_t<SIZE >= 2, Dummy>* = nullptr>
    Type y() const { return e[1]; };

    template<typename Dummy = void, std::enable_if_t<SIZE >= 3, Dummy>* = nullptr>
    Type z() const { return e[2]; };

    template<typename Dummy = void, std::enable_if_t<SIZE >= 4, Dummy>* = nullptr>
    Type w() const { return e[3]; };
};
Vector v1;
v1.x();
v1.y();
v1.z();
//v1.w(); // ERROR
    
Vector<int, 4> v2; 
v2.x();
v2.y();
v2.z();
v2.w(); // OK

Online Demo

  • Related