struct base {...">

C ++ CRTP Name Lookup

Why is this code not compiled (undeclared identifier "x", both g ++ 4.9 and clang ++ 3.5)?

template <class T> struct base { int x; }; template <class U> struct end : public base<U> { end() { x = 5; } }; 

Note. Explicitly defining this->x solves the problem.

+5
source share
2 answers

It does not compile because the dependent base classes are ignored during the name lookup, and base is the dependent base.

You can use the this pointer:

 end() { this->x = 5; } 

Or simply explicitly specify the base class:

 end() { base::x = 5; } 

Note:

  • See the relevant entry in the C ++ FAQ .
+6
source

Since sometimes you can use >> as a binary operator (right shift), this does not compile in gcc and clang (it compiles with MSVC 13).

A simple fix adds a space from >> to >> :

  class end : public middle<end<U> > 

It works:

 #include <iostream> using namespace std; class base { public: int x; }; template <class T> class middle : public base {}; template <class U> class end : public middle<end<U> > { public: end() { base::x = 5; } }; int main() { end<middle<base> > e; cout << ex << endl; return 0; } 
0
source

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


All Articles