Search code examples
c++c++20template-meta-programmingc++-concepts

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


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.


Solution

  • With concepts you can simply do

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