Why do some compilers insist on qualifying members of the public members of the base class of the template, rather than requiring the same for a class without a template? Please review the following code lists:
Template Class:
#include <iostream> using namespace std; template <class T> class TestImpl { public: // It wont make a difference even if we use a protected access specifier here size_t vval_; TestImpl(size_t val = 0) : vval_(val) { } }; template <class T> class Test : public TestImpl<T> { public: Test(size_t val) : TestImpl<T>(val) { cout << "vval_ : " << vval_ << endl; // Error: vval_ was not declared in this scope //! cout << "vval_ : " << TestImpl<T>::vval_ << endl; // this works, obviously } }; int main() { Test<int> test1(7); return 0; }
Class without template:
#include <iostream> using namespace std; class TestImpl { public: // It wont make a difference even if we use a protected access specifier here TestImpl(size_t val = 0) : vval_(val) {} size_t vval_; }; class Test : public TestImpl { public: Test(size_t val) : TestImpl(val) { cout << "vval_ : " << vval_ << endl; } }; int main() { Test test1(7); return 0; }
The significant difference between the above code lists is that while the first list uses the template classes, the second does not.
Both lists will now be compiled using the Microsoft Visual Studio Compiler (cl), but the first WONT list has been compiled with both the Digital Mars Compiler (dmc) and GNU Minimalist for Windows (MinGW - g ++). I will get an error, for example, "vval_ has not been declared in the scope" - an error that I obviously understand what this means.
If I access the public variable TestImpl vval _ using TestImpl <T> :: vval _ , the code works. In the second listing, compilers do not complain when the derived class accesses the vval _ base class variable without assigning it.
As for the two compilers, and possibly others, my question will be why should I be able to directly access (without qualification) the variable vval _ directly from the non-template class, inheriting from the class without the template , while I can't do the same from the template class inheriting from the template class ?
c ++ inheritance oop
John gathogo
source share