Search code examples
c++functiontypesabstract-class

Is there a way to get a derived class' type in a base class' function?


I'm looking for a way to use the type of a derived class in a function in the base class, similar to templatized functions.

class Base
{
    T foo() const
    {
        return T(*this);
    }
}

class Derived : public Base
{
}

This is similar to what I want to use this for, so that I don't have to override foo as a pure virtual function in every derived class. The goal is to find a way for T in foo to be the type of the derived class. For example, calling foo on an object of type Derived should call a version of foo that looks like this:

Derived foo() const
{
    return Derived(*this);
}

I know this probably isn't something you can do, but can anyone confirm?


Solution

  • Yes, you can make Base a template, and instantiate it with Derived when inheriting from it. This is referred to as the Curiously Recurring Template Pattern (CRTP):

    template<typename T>
    class Base
    {
      public:
        T foo() const
        {
            return T(*this);
        }
    };
    
    class Derived : public Base<Derived>
    {
    };
    

    Here's a demo.