Inheritance and templates in g++

M

Martin Steen

Hello,

I discovered a strange (?) template behaviour in g++.
It seems like I cannot access a variable from the baseclass
in a derived class without using a scope-operator or a cast.
This error doesn't occur with Borland C++. It also doesn't
occur when I don't use templates.

Is there a compiler-switch to change this behaviour?

template <typename T>
class CTest1
{
protected:

T a;
};

template <typename T>
class CTest2 : public CTest1<T>
{
public:

void Function1()
{
a = 0; // ERROR - a undeclared
}

void Function2()
{
CTest1<T>::a = 0; // WORKS
}

void Function3()
{
T(a) = 0; // WORKS
}
};

Best regards, Martin
 
M

mlimber

Martin said:
Hello,

I discovered a strange (?) template behaviour in g++.
It seems like I cannot access a variable from the baseclass
in a derived class without using a scope-operator or a cast.
This error doesn't occur with Borland C++. It also doesn't
occur when I don't use templates.

Is there a compiler-switch to change this behaviour?

template <typename T>
class CTest1
{
protected:

T a;
};

template <typename T>
class CTest2 : public CTest1<T>
{
public:

void Function1()
{
a = 0; // ERROR - a undeclared
}

void Function2()
{
CTest1<T>::a = 0; // WORKS
}

void Function3()
{
T(a) = 0; // WORKS
}
};

Best regards, Martin

See the FAQ:

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19

Cheers! --M
 
J

Jens Theisen

Martin Steen said:
Thank you, this is the answer I was looking for.
Seems like I have to live with that, although I still
think it's funny.

It's sad, but it has to be that way because C++'s grammar is
screwed. The parser needs to know if a symbol denotes an object, a
type or a template in order to parse correctly, but this information
can't be obtained during parsing itself in these cases; so the
programmer has to provide this information manually.

Regards,

Jens
 
J

Jens Theisen

Noah Roberts said:
What if that is changed slightly:

template < typename T >
class B
{
public:
void f() {}
};

class A : public B<int> {};

A a
a.f();

Does that work on all compilers?

You changed two things:

1. made the member be a function rather than a type
2. made the access, a.f(), be not dependent on a template parameter
(because we're not in a template at all)

Each of those changes alone would be sufficient to work on any
standards compliant compiler.

Regards,

Jens
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,118
Latest member
LatishaWhy
Top