notaorb
notaorb

Reputation: 2180

Error with using keyword with curiously recurring template pattern

Does anyone know why the following code compilation cannot find N::balance_type?

I'm using this example from Stroustrup C++ 4th Ed Page 771. It is the curiously recurring template pattern.

class Bal {};

template<typename N>
struct Node_base : N::balance_type {
};

template<typename Val, typename Balance>
struct Search_node : public Node_base<Search_node<Val,Balance>> {
    using balance_type = Balance;
};

int main()
{
    Search_node<int, Bal> sn;
    return 0;
}

Compilation:

clang++ -std=c++11 -Wall -pedantic test197.cc && ./a.out
test197.cc:4:23: error: no type named 'balance_type' in 'Search_node<int, Bal>'
struct Node_base : N::balance_type {
                   ~~~^~~~~~~~~~~~
test197.cc:8:29: note: in instantiation of template class
      'Node_base<Search_node<int, Bal> >' requested here
struct Search_node : public Node_base<Search_node<Val,Balance>> {
                            ^
test197.cc:14:27: note: in instantiation of template class
      'Search_node<int, Bal>' requested here
    Search_node<int, Bal> sn;
                          ^
1 error generated.

Upvotes: 2

Views: 60

Answers (1)

Łukasz Ślusarczyk
Łukasz Ślusarczyk

Reputation: 1864

g++ says SearchNode is an incomplete type when you derive from Node_base<Search_node<Val,Balance>>

test.cpp: In instantiation of ‘struct Node_base<Search_node<int, Bal> >’:
test.cpp:8:8:   required from ‘struct Search_node<int, Bal>’
test.cpp:14:25:   required from here
test.cpp:4:8: error: invalid use of incomplete type ‘struct Search_node<int, Bal>’
 struct Node_base : N::balance_type {
        ^~~~~~~~~
test.cpp:8:8: note: declaration of ‘struct Search_node<int, Bal>’
 struct Search_node : public Node_base<Search_node<Val,Balance>> {

I guess using SearchNode in this place is invalid because you are defining it right now.

Upvotes: 5

Related Questions