views:

501

answers:

4

In visual C++, I can do things like this:

template <class T>
class A{
protected:
    T i;
};

template <class T>
class B : public A<T>{
    T geti() {return i;}
};

If I try to compile this in g++, I get an error. I have to do this:

template <class T>
class B : public A<T>{
    T geti() {return A<T>::i;}
};

Am I not supposed to do the former in standard C++? Or is something misconfigured with gcc that's giving me errors?

+1  A: 

This should work as far as I know... probably some setting of gcc.

Nick
I did actually oversimplify it now that I look at it. I forgot to include that I was using a template.
Jason Baker
+5  A: 

This used to be allowed, but changed in gcc 3.4.

In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,

    template <typename T> struct B {
      int m;
      int n;
      int f ();
      int g ();
    };
    int n;
    int g ();
    template <typename T> struct C : B<T> {
      void h ()
      {
        m = 0; // error
        f ();  // error
        n = 0; // ::n is modified
        g ();  // ::g is called
      }
    };

You must make the names dependent, e.g. by prefixing them with this->. Here is the corrected definition of C::h,

    template <typename T> void C<T>::h ()
    {
      this->m = 0;
      this->f ();
      this->n = 0
      this->g ();
    }
Brian R. Bondy
Heh... you must have posted at the same time I did. It's strange that msvc accepts that even though it's invalid (and was causing weird runtime errors).
Jason Baker
Ya, I seen your post right after I found the release notes. I think probably old versions of both gcc and vc++ supported the wrong way. But gcc chose to make it right and vc++ chose to keep backwards compatibility.
Brian R. Bondy
+2  A: 

I figured this one out:

Apparently, the first example ISN'T valid C++ and it's bad that msvc takes this. There are solutions posted on the C++ faq lite.

Jason Baker
+1  A: 

You may want to read about two-phase name lookup

Nemanja Trifunovic