Making a method available depending on a compile-time argument

c++, c++11

Solution

For example, you can declare your function as template and use `std::enable_if` like this

template<typename DataType, int Dimension>
class Coord
{
private:
    std::array<DataType, Dimension> _data;

public:
    template <class T = DataType>
    typename std::enable_if<Dimension >= 3, T&>::type
    z()
    {
        return _data[2];
    }
};

Problem

Is there a way to compile a method or not, depending on template argument ? I'm trying to create a Coordinate class that can handle 2, 3 or more dimensions. I want to provide acces methods as `x()`, `y()` and `z()`, but I would like `z()` method to be accessible only if dimension is larger than 3. For now (as you can see below), I use a `static_assert` to prevent use of `z()` for coordinates of dimension 2. ``` template<typename DataType, int Dimension> class Coord { private: std::array<DataType, Dimension> _data; public: // how to achieve some kind of compile_if() DataType& z() { static_assert(Dimension >= 3, "Trying to access an undefined dimension."); return _data[2]; } }; ``` What I would like to do is hide existence of `z()` for dimension 2, so that this ``` Coord<int, 2> ci2(0,0); ci2.z() = 3; // shouldn't compile ``` doesn't compile without the use of static_assert. I've seen many question around std::enable_if, but for what I understand it is use to enable or disable specific overloads. Question is : is there a way to make a method available or not depending on a compile-time argument ?

Original source

Related problems