Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ CRTP Name Lookup

Why does this code fail to compile (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 specifying this->x solves the problem.

like image 449
Robert Mason Avatar asked Oct 26 '14 06:10

Robert Mason


1 Answers

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

You can use the this pointer :

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

Or just explicitly name the base class :

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

Note:

  • See the relevant entry in the C++ FAQ.
like image 145
quantdev Avatar answered Oct 23 '22 20:10

quantdev