Undefined template argument for base class

I am quite sure that I read the reason why the compiler cannot handle this code somewhere in SO, but after several hours of searching I still can not find it. Here is the relevant code:

#include <iostream> template <typename T> class base { }; class derived : base<derived::myStruct> { public: struct myStruct { }; }; int main () { return 0; } 

The problem is that the parser first tries to generate the base<derived::myStruct> before parsing derived , and thus I get this error: "error C2065:" myStruct ": undeclared identifier". As a silly trick, I noticed that VS2010 stops complaining if I declare struct myStruct; just above class derived . In my opinion, myStruct should be bound inside derived , and this code should cause the same error:

 #include <iostream> template <typename T> class base { }; struct myStruct; class derived : base<derived::myStruct> { public: struct myStruct { }; }; int main () { return 0; } 

Update : gcc-4.5.1 may throw the expected error , so I think the above is an error in VS2010 ...

+4
source share
3 answers

A myStruct is to declare myStruct outside of derived .

 #include <iostream> template <typename T> class base { }; struct derived_myStruct { }; class derived : base<derived_myStruct> { public: typedef derived_myStruct myStruct; }; int main () { return 0; } 

In more complex cases where derived is a template class, derived_myStruct will also be a template class with the same template parameters (or just a subset), and you will pass them through.

+1
source

derived::myStruct is simply an incomplete type at this point. Your second example should not work either, unfortunately the MSVC compiler accepts a lot of corrupted template code. One work is to use an intermediate class to ensure that the type is complete:

 template <typename T> class base { }; class middle { public: struct myStruct { }; }; class derived : public middle, base<middle::myStruct> { }; int main () { return 0; } 
+2
source

In C ++, you can only refer to names after they are defined. Since derived is not explicitly defined yet, when you reference a class nested inside derived to define a base class, this will not work. The exception to what was declared after they were available are the member function bodies defined in the class definition: they are treated as if they were defined after the class definition.

+1
source

Source: https://habr.com/ru/post/1446575/


All Articles