lundi 6 mai 2019

Would the C++11 targeted constructor allow me to safely initialize derived class from template constructor?

I have a variety of objects created from template class bar (below). Each object has a data member with different data type (eg std::string, bool, int, etc.)

I have a set of current defaults of each of the derived/templated types in a static array that have been constructed via new.

I'd like to initialize the object in the constructor, WITHOUT a separate initialization step.

I can be certain that the type of default object I'm retrieving from the static array is absolutely the SAME templated type.

I figure I'm running into the problem that object bar isn't really of type object bar until the constructor finishes? Isn't there a way in C++11 to use targeted or delegate constructors to work around that?

class foo
{
public:
    foo(int index) : fMyIndex(index) { }

protected:
    int fMyIndex;

};

template<class T>
class bar : public foo
{
public:
    // This constructor takes the integer prefIndex, then constructs
    // the object based on current in-memory settings, which it obtains from a static array via static GetDefaultData;
    //
    bar(int index) : foo(index)
    {
        // get the most current version of the in-memory data.  defaultObject is a pointer to a "BarString"
        foo* defaultObject = static_cast<bar*>(GetDefaultData(fMyIndex));
        if (defaultObject) {
            // bad memory access!
            *this = *defaultObject;
        }
    }

private:
    T fMyData;

};


typedef bar<std::string> BarString;
typedef bar<int> BarInt;
typedef bar<bool> BarBool;

Aucun commentaire:

Enregistrer un commentaire