check if member exists using enable_if

前端 未结 6 1297
鱼传尺愫
鱼传尺愫 2020-11-28 13:40

Here\'s what I\'m trying to do:

template  struct Model
{
    vector vertices ;

    #if T has a .normal member
    void transform(         


        
6条回答
  •  眼角桃花
    2020-11-28 13:57

    This has become way easier with C++11.

    template  struct Model
    {
        vector 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 struct int_ { typedef int type; };
    
        template::type = 0>
        void modifyNormal(Lhs &&lhs, Rhs &&rhs, special_) {
           lhs.normal = rhs * lhs.normal;
        }
    
        template
        void modifyNormal(Lhs &&lhs, Rhs &&rhs, general_) {
           // do nothing
        }
    };
    

    Things to note:

    • You can name non-static data members in decltype and sizeof without needing an object.
    • You can apply extended SFINAE. Basically any expression can be checked and if it is not valid when the arguments are substituted, the template is ignored.

提交回复
热议问题