vendredi 28 avril 2017

Is it possible to switch to a different base class constructor at runtime?

Suppose I'm writing Derived and have to inherit from Base, which I don't control and has two separate constructors and a deleted copy and move constructors:

struct Base {
    Base(int i);
    Base(const char *sz);
    Base(const Base&) = delete;
    Base(const Base&&) = delete;
};

struct Derived {
    Derived(bool init_with_string);
};

Now, depending on the value of another_param I have to initialize my base class using either a constructor or the other; if C++ was a bit less strict it would be something like:

Derived::Derived(bool init_with_string) {
    if(init_with_string) {
        Base::Base("forty-two");
    } else {
        Base::Base(42);
    }
}

(this would also be useful for all the cases where it's cumbersome to calculate values to pass to base class constructors/fields initializers in straight expressions, but I'm digressing)

Unfortunately, even if I don't see particular codegen or object-model obstacles to this kind of thing, this isn't valid C++, and I cannot think of easy workaround.

Is there some way around this that I'm not aware of?

Aucun commentaire:

Enregistrer un commentaire