I just need a quick C++ template sanity check. The following code compiles successfully on GCC:
#include <iostream>
using namespace std;
template <typename Type>
class Base
{
protected:
Type value;
};
template <typename Type>
class Derived : public Base<Type>
{
public:
Type getValue()
{
return Base<Type>::value;
}
};
int main(int argc, char** argv)
{
Derived<int> derived;
cout << "Hello " << derived.getValue() << endl;
return 0;
}
However, if I remove the 'Base<Type>::' part from inside getValue() then it no longer compiles. That is, the code:
#include <iostream>
using namespace std;
template <typename Type>
class Base
{
protected:
Type value;
};
template <typename Type>
class Derived : public Base<Type>
{
public:
Type getValue()
{
return value;
}
};
int main(int argc, char** argv)
{
Derived<int> derived
cout << "Hello " << derived.getValue() << endl;
return 0;
}
Gives the error:
main.cpp: In member function ‘Type Derived<Type>::getValue()’:
main.cpp:18: error: ‘value’ was not declared in this scope
This surprises me, as I didn't think you needed to clarify the variable in that way as it is a member of the base class.
If I modify the classes to not be templatised then I don't need the 'Base<Type>::' prefix, so why do I need it in the templated case? Is the mistake elsewhere - maybe I'm doing template inheritance wrong?
Thanks!