Deriving a class from a class template

后端 未结 3 510
青春惊慌失措
青春惊慌失措 2021-01-21 16:37

I am new to C++. During my learning phase I encountered with below issue. I am trying to derive a class stack from a class template Queue. Compiler thr

3条回答
  •  梦毁少年i
    2021-01-21 16:52

    The reason is that inside a template, two-phase name lookup rules apply:

    • Names which do not depend on template parameters are looked up (=resolved) when the template is defined (=parsed).

    • Names which do depend on template parameters are looked up when the template is instantiated (when you provide the template arguments).

    • Base classes which depend on template parameters are only searched during name lookup at instantiation time.

    The reason for this two-phase lookup is that until the template arguments are known, the compiler cannot know what the definition of the base class (or other dependent construct) will be. Remember that template specialisation exists.

    You need to somehow tell the compiler that the name b is dependent. You basically have three ways to do that:

    1. Prefix the name with this->; since you're in a class template, all your members depend on template parameters implicitly:

      this->b = a;
      
    2. Use full qualification for the name. This will make the dependency on template parameters explicit:

      Queue::b = a;
      
    3. Put a using declaration into your class to inform the compiler that the name comes from a dependent base class:

      template 
      class stack :public Queue // Derived class
      {
      protected:
          using Queue::b;
      
      public:
          stack():Queue()
          {
              b=a;
          }
           void pop()
          {
              b--;
          }
      };
      

提交回复
热议问题