Derived template-class access to base-class member-data

前端 未结 3 643
天涯浪人
天涯浪人 2020-11-22 00:45

This question is a furtherance of the one asked in this thread.

Using the following class definitions:

template 
class Foo {

public:
         


        
3条回答
  •  既然无缘
    2020-11-22 01:34

    Here the base class is not a nondependent base class( which means one with a complete type that can be determined without knowing the template arguments), and _foo_arg is a nondependent name. Standard C++ says that nondependent names are not looked up in dependent base classes.

    To correct the code, it suffices to make the name _foo_arg dependent because dependent names can be looked up only at the time of instantiation, and at that time the exact base specialization that must be explored will be known. For example:

    // solution#1
    std::cout << this->_foo_arg << std::endl;
    

    An alternative consists in introducing a dependency using a qualified name:

    // solution#2
    std::cout << Foo::_foo_arg << std::endl;
    

    Care must be taken with this solution, because if the unqualified nondependent name is used to form a virtual function call, then the qualification inhibits the virtual call mechanism and the meaning of the program changes.

    And you can bring a name from a dependent base class in the derived class once by using:

    // solution#3
    template 
    class Bar : public Foo {
    public:
        ...
        void BarFunc ();
    private:
        using Foo::_foo_arg;
    };
    
    template 
    void Bar::BarFunc () {
        std::cout << _foo_arg << std::endl;   // works
    }
    

提交回复
热议问题