2

I have some trouble in reading some source codes from Eigen library. Here is the base class TensorBase:

template<typename Derived>
class TensorBase<Derived, ReadOnlyAccessors> {
  ...
};

In the following code, How can the base class TensorBase inherit itself? What's the point of using this inheritance? Is this common?

template<typename Derived, int AccessLevel = 
         internal::accessors_level<Derived>::value>
class TensorBase : public TensorBase<Derived, ReadOnlyAccessors> {
  ...
};
Nishant Singh
  • 4,177
  • 1
  • 17
  • 17
Yulong Ao
  • 1,199
  • 1
  • 14
  • 22

1 Answers1

4

The class is not inheriting from itself. It is inheriting from a different instantiation of the same template. Remember, different instantiations of the same template are different types.

For illustration, consider this simple albeit contrived example:

#include <iostream>
using namespace std;

template <int N>
struct foo : foo<N-1> {};

template <> 
struct foo<0> {
    static const int value = 23;
};


int main() {
    std::cout << foo<23>::value;
    return 0;
}

foo<23> inherits from foo<22> which in turn inherits from foo<21> and so on until eventually foo<0> does not inherit from anything.

In your case it seems like read-only functionality is implemented in a base class that is inherited from the instantiations for different access levels.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185