CRTP Hack: Turning Protected Inside-Out

Vladimir Sakharuk 1 min read
programming

This hack is useful when you already have many derived classes. In C++, protected members are accessible only from derived classes, but with CRTP it’s often convenient to access them from the base. A trivial fix is to add friend declarations to all classes, and Cursor can help churn those.

Another solution is:

a.cpp
cpp
#include <iostream>

template<typename D>
struct Base
{
    struct Accessor: public D
    {
        friend struct Base<D>;
    };

  bool amI() {
    if constexpr (requires { static_cast<Base::Accessor*>(this)->TheOne; })
        std::cout<<"I am The One"<<std::endl;
    return true;
   }
};

class Derived: public Base<Derived>
{
 protected:
   static constexpr size_t TheOne = 1;
};


int main()
{
    Derived the_one;
    the_one.amI();
    return 0;
}