Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

Writing a recursive base class concept in C++

In C++, I want to restrict the template parameter T of class Foo<T> to strictly be an inheritor of Foo<T>. To do this, I write the following:

template <typename TSelf> class Foo;

template <typename TSelf>
  requires (is_base_of<Foo<TSelf>, TSelf>)
class Foo
{
};

The error I get is

'Foo': requires clause is incompatible with the declaration

How can I fix this?

Upvotes: 1

Views: 198

Answers (1)

Jarod42
Jarod42

Reputation: 217235

Within CRTP, derived class is incomplete.

You might add that assertion inside a method which should be called, as destructor:

template <typename TSelf>
class Foo
{
    // ...
    ~Foo() { static_assert(std::is_base_of_v<Foo<TSelf>, TSelf>); }
    // ...
};

Upvotes: 2

Related Questions