vendredi 30 novembre 2018

CRTP base constructor crashes because child is not constructed

I have classes which are autogenerated but I want to enable end users to add custom member functions and constructors.

My approach is to use a CRTP base class which has no member variables just functions.

The problem lies with the constructor. If I define a constructor in my CRTP I cannot correctly access the child as it is not constructed yet as the child classes constructor only gets called after the CRTP base is constructed.

#include <iostream>
#include <string>

template<class Child>
struct Foo {
  Foo(std::string i) {
    // Childs constructor is not run yet.
    std::cout << static_cast<Child&>(*this).d.size(); // Prints trash
    static_cast<Child&>(*this).d = i; // Segfault here
    (void) i;
  }
};

// Cannot change this class.
struct Bar : Foo<Bar> {
  using base_t = Foo<Bar>;
  using base_t::base_t;
  std::string d;
};


int main()
{
  Bar bar("asdgasdgsag");
  std::cout << "bar.d: " << bar.d << std::endl;
}

Is there a way to solve this problem?

Aucun commentaire:

Enregistrer un commentaire