Illegal reference to a non-static member ... typedef?

Why am i getting

Error C2597: Illegal reference to a non-static element 'derived<<unnamed-symbol>>::T'

when am I trying to compile this code in Visual C ++ 2010 x64? (Seems good on x86 ... which one is correct?)

 struct base { typedef int T; }; template<class> struct derived : base { using base::T; derived(T = T()) { } }; int main() { derived<int>(); return 0; } 
+4
source share
3 answers

As noted in a Praetorian comment, the problem is with the default T() value. Based on the error data, using base::T seems to confuse the compiler in finding T() as calling a non-static base member function, rather than building an instance of type T

Here's an interesting fix that works in MSVC 2005 x86 (I haven't tried any other compiler yet). Note that T() saved. This either removes the ambiguity of using base::T , or simply causes T to refer to the inherited type, not to using (which, apparently, is not the same for the compiler).

 //... template<class> struct derived : base { using base::T; derived(T = static_cast<T>( T() )) { } //No error }; //... 

Edit: try changing the base to this and see what error messages you get:

 struct base { struct T{T(){}}; }; 

I get the original C2597 , but also this one:

error C2440: "default argument": cannot be converted from '' to 'base :: T' The constructor cannot use the source type, or the resolution of the constructor overload was ambiguous.

I don't know what the compiler means, '' but this is probably a similar problem with the original base definition. This compiles if I delete the line using base::T; .

+3
source

Why are you using using base::T ? Types defined in the base class will be automatically available in the derived class.

 struct base { typedef int T; }; template< class X > struct derived : base {}; derived<int>::T v = 0; // this is OK in C++ 
0
source

Use this instead (should be clear):

 template<class T> struct derived : base { derived(T = T()) { } }; 
0
source

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


All Articles