SFINAE Based on Class Member Existence/Absence

Viewed 388

I have a basic understanding of SFINAE, e.g. how enable_if works. I recently came across this answer, and I've spent over an hour trying to understand how it actually works to no avail.

The goal of this code is to overload a function based on whether a class has a specific member in it. Here's the copied code, it uses C++11:

template <typename T> struct Model
{
    vector<T> vertices;

    void transform( Matrix m )
    {
        for(auto &&vertex : vertices)
        {
          vertex.pos = m * vertex.pos;
          modifyNormal(vertex, m, special_());
        }
    }

private:

    struct general_ {};
    struct special_ : general_ {};
    template<typename> struct int_ { typedef int type; };

    template<typename Lhs, typename Rhs,
             typename int_<decltype(Lhs::normal)>::type = 0>
    void modifyNormal(Lhs &&lhs, Rhs &&rhs, special_) {
       lhs.normal = rhs * lhs.normal;
    }

    template<typename Lhs, typename Rhs>
    void modifyNormal(Lhs &&lhs, Rhs &&rhs, general_) {
       // do nothing
    }
};

For the life of me, I can't wrap my head around how this mechanism works. Specifically, what does typename int_<decltype(Lhs::normal)>::type = 0 help us do, and why do we need an extra type (special_/general_) in this method.

3 Answers
Related