Deducing this and CRTP

Deducing this and CRTP

The new deduce this has the functionality of overlapping with CRTP, where one can get the concrete type of a subclass without passing it as a template parameter of the base class, this can be very useful if the inheritance relationship is complex. So, should that be always preferred to CRTP?

I was trying to move the commented out old CRTP to the following say implementation:

template <class T>
struct Animal {
    string name;
    // void say() { cout << static_cast<T *>(this)->category() << ' ' << name << '\n'; }
    void say(this auto &self) { cout << self.category() << ' ' << name << '\n'; }
};
struct Cat : Animal<Cat> {
    string category() { return "cat"; }
};

but got

program.cpp: In explicit object member function 'void Animal<T>::say(this auto:58&)':
program.cpp:7:71: error: invalid use of non-static data member 'Animal<T>::name'
    7 |         void say(this auto &self) { cout << self.category() << ' ' << name << '\n'; }
      |                                                                       ^~~~

The reason for this is the deduce this function is a free function with an object parameter, as opposed to traditional free function or member function. The design choice was:

This allows for the clearest model of what a this-annotated function is: it is a static member function that offers a more convenient function call syntax. There is no implicit this in such functions, the only mention of this would be the annotation on the object parameter. All member access must be done directly through the object parameter.

If you are one like me who doesn't like writing this->, there's a trade off between the simplicity of the class parameters and more verbosity of self.. Personally I dislike the fact that the function is inside the class and I cannot use this implicitly,


Encryption for secure online storage