C ++ and CRTP pattern implementation and compiler dilemma

I am trying to compile the following bit of code, however there seems to be a problem that I cannot solve:

template <int x> struct count_x { enum { x_size = x }; }; template <typename y> struct crtp_base { typedef typename y::count_t count_t; crtp_base(const count_t&){} }; template <int x> struct derived : public crtp_base<derived<x> > { typedef typename count_x<x> count_t; typedef crtp_base<derived<x> > base_t; derived(const count_t& c) : base_t(c){} }; int main() { derived<2> d((count_x<2>())); return 0; } 

When compiling wth clang 3.1, the following error:

 c:\clangllvm\code\example.cc:18:21: error: expected a qualified name after 'typename' typedef typename count_x<x> count_t; ^ c:\clangllvm\code\example.cc:18:21: error: typedef name must be an identifier typedef typename count_x<x> count_t; ^~~~~~~~~~ c:\clangllvm\code\example.cc:18:28: error: expected ';' at end of declaration list typedef typename count_x<x> count_t; ^ ; c:\clangllvm\code\example.cc:20:18: error: no template named 'count_t'; did you mean 'count_x'? derived(const count_t& c) ^~~~~~~ count_x c:\clangllvm\code\example.cc:2:8: note: 'count_x' declared here struct count_x ^ c:\clangllvm\code\example.cc:20:18: error: use of class template count_x requires template arguments derived(const count_t& c) ^ c:\clangllvm\code\example.cc:2:8: note: template is declared here struct count_x ^ 5 errors generated. 

I believe that it has something to do with how templates are defined at compile time, and if they are defined as a type at the right time. I also tried adding "using base_t :: count_t;" to no avail. In addition, the diagnostics created by the compiler left me really lost. A response or reading suggestion about this error will be appreciated.

+6
source share
1 answer

count_x<x> not a qualified name (it does not matter at all :: !), therefore it cannot be surpassed by typename .

Once you fix this, the code will still fail, because the nested typedefs of the derived type were not noticed by the compiler when creating the CRTP database instance. This other question shows some alternatives.

+2
source

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


All Articles