g++ 4.x template hiba

Fórumok

Van egy ilyen kódom:

template <class __T>
class C1
{
    public:
    C1 (int t) {my_data = t;};
    int my_data;
};

template <class __T>
class C2: public C1< __T>
{
    public:
    void dosomething () {
        my_data = 0;
    };
};

g++ 3-as szériával még szépen lefordul*, de a 4.x-el azt mondja, hogy a 14. sorban

‘my_data’ was not declared in this scope

. Érdekes módon, ha például úgy írom, hogy

C1<__T>::my_data = 0;

, vagy akár

this->my_data = 0

, akkor megeszi. Hibás a kódom, vagy bugos a g++?
*Szerk: g++3.3-al megy, 3.4-el már nem.

Hozzászólások

Hirtelen nem tudtam a választ, úgyhogy megkérdeztem ##c++ channel-en:

<imp> geordi: template<typename T> class B { public: int data; }; template<typename T> class D : public B<T> { public: void func() { i=0; } }; int main() {}
<geordi> error: 'data' was not declared in this scope
<imp> ^^ any reason for that?
<Anduin> imp: name depends on the type
...
<Adrinael> imp, two-phase name lookup
<Adrinael> 'data' cannot be found on the first phase, but making the name dependent, it's looked up in the second phase where templates are expanded.

Effective C++, 3d Edition, Item 43: Know how to access names in templatized base classes.
Az egyik kedvenc könyvem ;-).