C++ template gotchas

后端 未结 4 792
梦谈多话
梦谈多话 2020-12-07 18:08

just now I had to dig through the website to find out why template class template member function was giving syntax errors:

template class F00         


        
4条回答
  •  星月不相逢
    2020-12-07 18:47

    I got tripped up the first time I inherited a templated class from another templated class:

    template
    class Base {
        int a;
    };
    
    template
    class Derived : public Base {
        void func() {
            a++; // error! 'a' has not been declared
        }
    };
    

    The problem is that the compiler doesn't know if Base is going to be the default template or a specialized one. A specialized version may not have int a as a member, so the compiler doesn't assume that it's available. But you can tell the compiler that it's going to be there with the using directive:

    template
    class Derived : public Base {
        using Base::a;
        void func() {
            a++; // OK!
        }
    };
    

    Alternatively, you can make it explicit that you are using a member of T:

    void func {
        T::a++; // OK!
    }
    

提交回复
热议问题