Home > Mobile >  How to make a template class that force it's child class to extends itself?
How to make a template class that force it's child class to extends itself?

Time:07-27

I would like to know the C equivalent of the following Java code.

public Class MyClass <T extends MyClass<T>> {...}

I have tried the following but failed using C11:

template <class T> class Parent {
    static_assert(std::is_base_of<Parent<T>, T>::value);
public:
    T* next;
};

class Child: public Parent<Child> {
public:
    Child* next;
};

Which results in:

incomplete type `Child` used in type trait expressions

CodePudding user response:

Unfortunately, within CRTP, T is an incomplete type (so most traits won't work on it).

You might add the check in a member instead (type would be complete at that point).

Good candidates are constructor and destructor:

template <class T>
class Parent
{
    // T is incomplete here.
public:
    ~Parent() noexcept
    {
       // T is complete here.
       static_assert(std::is_base_of<Parent<T>, T>::value);
    }
public:
    T* next;
};
  •  Tags:  
  • c
  • Related