3

It works fine for non-template classes (the below code with the "template" lines commented out and deriving 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 I fix it?

Thomas
  • 4,208
  • 2
  • 29
  • 31
  • You don't. This looks like a compiler bug, in whatever compiler you're using. – user207421 Sep 04 '14 at 09:52
  • 8
    @EJP Yes you do. This is not a bug. The name lookup for `i_` skips base classes whose type depends on a template parameter. – T.C. Sep 04 '14 at 09:52
  • http://www.parashift.com/c++-faq/nondependent-name-lookup-members.html – user657267 Sep 04 '14 at 09:55
  • 5
    @EJP To add to T.C.'s comment, unqualified lookup *cannot* look in dependent base classes, because the base classes may not even be defined yet. You may add specialisations of `Base` after the definition of `Deriv`, and those specialisations may omit `i_`. –  Sep 04 '14 at 09:56
  • Entry in [tag:c++-faq] here on SO: [Why doesn't a derived template class have access to a base template class' identifiers?](http://stackoverflow.com/q/1239908/1782465) – Angew is no longer proud of SO Sep 04 '14 at 10:01

0 Answers0