1

This code produces an error in the GNU compiler:

class A
{
public:
    int X;
};

template<class T>
class Foo : public T
{
public:
    void doStuff();
};

template<class T>
void Foo<T>::doStuff()
{
    X++;
}

There is already an answer for why this is an error. I would like to know if there is another way of working around this error rather than using

T::X

every time I want to reference the X member. I tried this:

template<class T>
void Foo<T>::doStuff()
{
    using T::X;
    X++;
}

But GCC gives an error: "a class-qualified name is not allowed"

Community
  • 1
  • 1
camomilk
  • 763
  • 1
  • 7
  • 15
  • obviously you cannot do `using T::X;` inside the function. You need to do this as shown here : http://www.ideone.com/MI9fM ... see my answer for other alternatives. They're not as good as this, but being aware of them helps sometimes! – Nawaz Feb 11 '11 at 21:42

4 Answers4

8

using T::X should work. If it gives error, there is some other problem with your code, or it must be compiler bug. See yourself : http://www.ideone.com/MI9fM


  • You may use this pointer, as

    template<class T>
    void Foo<T>::doStuff()
    {
        this->X++;
    }
    

    This gives compiler a hint where to look for the symbol X.

Demo: http://www.ideone.com/NIucO


  • You can also do this:

    template<class T>
    void Foo<T>::doStuff()
    {
         T::X++;
    }
    

Demo : http://www.ideone.com/PswvG

Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

This would also work:

this->X++;

That would tell the compiler than since it sees X is not a member of the derived class, it has to come from the template base and there is no need to worry about it.

UncleBens
  • 40,819
  • 6
  • 57
  • 90
1
class A
{
public:
    int X;
};

template<class T>
class Foo : public T
{
public:
    using T::X;
    void doStuff();
};

template<class T>
void Foo<T>::doStuff()
{
    X++;
}

int main()
{
    Foo<A> o;
    o.doStuff();
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • This is what I was missing, I put the using T::X in the doStuff() function instead of the class declaration. – camomilk Feb 11 '11 at 21:32
0

Maybe this will work? Just guessing:

int &X = T::X;

This will create an alias that can be used within a block of code, similarly to the using T::X you tried that didn't work.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622