Calling a base class method in a template virtual class hierarchy

后端 未结 2 581
野趣味
野趣味 2020-12-19 13:41

Let\'s say I have the following class hierarchy:

template< class T >
class TestBase {

public:

    virtual T const & do_foo() = 0;

};

template&l         


        
相关标签:
2条回答
  • 2020-12-19 14:19

    It will not win any awards for it's beauty, but this piece of code works as expected, without the compiler complaining.

    virtual int do_bar() {
        return ((TestBase<T> *) this)->do_foo() + 1;
    }
    
    0 讨论(0)
  • 2020-12-19 14:34

    Non-dependent names (that is, names which do not depend on template arguments), are looked up when parsing the template, not when instantiating it. You need to make do_foo a dependent name. There are basically two ways to achieve this:

    virtual int do_bar() {
        return this->do_foo() + 1;
    }
    

    or

    template< class T >
    class TestDerived : public virtual TestBase< T > {
    
    public:
        using TestBase<T>::do_foo;
    
        virtual int do_bar() {
            return do_foo() + 1;
        }
    
    };
    
    0 讨论(0)
提交回复
热议问题