Reputation: 195
I'm having difficulty understanding why there is a difference in the following two pieces of code, what exactly is the compiler doing.
I have the following bit of trivial code, that compiles without any problems as expected:
class base
{
public:
typedef int booboo;
};
class derived : public base
{
public:
int boo()
{
booboo bb = 1;
return bb;
}
};
int main()
{
derived d;
d.boo();
return 0;
}
I take the code from above and add some template parameters, and begin to get errors relating the type booboo not being valid:
template <typename T>
class base
{
public:
typedef T booboo;
};
template <typename T>
class derived : public base<T>
{
public:
//typedef typename base<T>::booboo booboo; <-- fixes the problem
booboo boo()
{
booboo bb = T(1);
return bb;
}
};
int main()
{
derived<int> d;
d.boo();
return 0;
}
Error:
prog.cpp:13:4: error: ‘booboo’ does not name a type
prog.cpp:13:4: note: (perhaps ‘typename base<T>::booboo’ was intended)
prog.cpp: In function ‘int main()’:
prog.cpp:23:6: error: ‘class derived<int>’ has no member named ‘boo’
.
I would like to understand in details, how a typical c++ compiler goes about compiling the template version of the code, how it differs from compiling the original example, is this an issue to do with multiple passes of the code, and type dependent look-ups?
Upvotes: 2
Views: 1943
Reputation: 477040
In the second version, booboo
is a dependent name, so it is not automatically visible in the template. You can either add using typename base<T>::booboo;
to the derived class, or use your typedef solution, or say typename base<T>::booboo bb = T(1);
.
Upvotes: 3