" in tempate derived classes? It works fine for classes other than templates (the code below with "template" strings, comm...">

Why do I need "this->" in tempate derived classes?

It works fine for classes other than templates (the code below with "template" strings, commented out and inferred from Base, not Base <T>.

#include<iostream>

template<typename T>
class Base {
 public:
  int i_;
};

template<typename T>
class Deriv: public Base<T> {
 public:
  void foo() {

    // This works.                                                                                                                                 
    std::cout << this->i_ << std::endl;

    /* This fails:
       tmpl.cc:14:18: error: ‘i_’ was not declared in this scope
            std::cout << i_ << std::endl;
    */
    std::cout << i_ << std::endl;
  }
};

      

Why? And how do you fix it?

+3


source to share





All Articles