lundi 28 août 2017

Accessing all derived children from parent in singleton

I am trying to write a singleton parent class that could be used as a basic accessor for all of its derived children, and getting stuck on wrapping my mind around the logic. I wrote some code, but it doesn't compile :(

Also, I am not sure if I am using the design pattern right either -- maybe I am supposed to use some other one?

Below is the code that I am trying to compile. The main point of the final code is to have a singleton for global configuration, and the children are configuration classes for different parts of the program.

template <struct T>
struct Parent {
    T* operator[](std::string child) {
        return dynamic_cast<T*>(children_[child]);
    }
    static const T& getInstance() {
        if (!one_parent_to_rule_them_all_) 
            one_parent_to_rule_them_all_ = new Parent;
        return dynamic_cast<T>(*one_parent_to_rule_them_all_); 
    }
    std::string Dump() {
        std::string res = "";
        for (const auto& child : children_) {
            res += child.second->Dump();
        }
        return res;
    }
protected:
    Parent() = default;
    Parent(std::string child_name, Parent* child) {
        children_[child_name] = child;
    }
    static Parent* one_parent_to_rule_them_all_;
    static std::map<std::string, Parent*> children_;
};

struct Child1 : Parent<Child1> {
    Child1() : Parent("child1", this);
    int foo = 0;
    std::string Dump() {
       return std::string(foo); 
    }
};

// More children here!

class ICanHazParentz {
// This class wants to have an instance of the parent, 
// without specifying the children
public:
    Parent p;
    void Dump() {
        std::cout << Parent::Dump() << std::endl;
    } 
}

class ICanHazChild1 {
// This class wants to have access to a child, 
// without specifying the parent
public:
    void Dump() {
        std::cout << Parent::getInstance()["child1"]->Dump() << std::endl;
    } 
}

int main() {
    Child1 c1;
    // More children
    ICanHazParentz ichp;
    ichp.Dump();
}

Although the current code looks silly, it is just an oversimplification of the final code.

Aucun commentaire:

Enregistrer un commentaire