C++ templates hides parent members

前端 未结 3 803
野性不改
野性不改 2021-02-10 03:55

Usually, when A is inheriting from B, all the members of A are automatically visible to B\'s functions, for example



        
3条回答
  •  遥遥无期
    2021-02-10 04:18

    It's a common issue, it is however perfectly possible to circumvent it, be it for functions, types or attributes.

    The problem comes up with the implementation of the 2 phases evaluation of template classes and functions. Normally the standard requires that the templates be evaluated two times:

    • A first time when encountered, to validate that it's correctly formed
    • The second when instanciated, to actually produce the code for the types given

    During the first evaluation, the template parameters are unknown, so it's impossible to tell what the base class is going to be... and notably if it contains a a member. Any symbol that does not depend on one of the template parameters is expected to be clearly defined and will be checked.

    By explicitly defining the scope you will delay the check to the second evaluation by making the symbol dependent on template parameters.

    Using Boost as inspiration:

    template 
    class MyClass: public Base
    {
    public:
      typedef Base base_;
    
      void foo()
      {
        // Accessing type
        bar_type x;             // ERROR: Not dependent on template parameter
        typename base_::bar_type x;
    
        // Accessing method
        bar();                  // ERROR: Not dependent on template parameter
        this->bar();
        base_::bar();
    
        // Accessing attribute
        mBar;                   // ERROR: Not dependent on template parameter
        this->mBar;
        base_::mBar;
      };
    
    }; // class MyClass
    

    I like the Boost idiom of defining a base_ inner typedef. First it certainly helps to define the constructors and second by explicitly qualifiying what comes from the Base class it makes things clear for those treading through the code.

提交回复
热议问题