1

Possible Duplicate:
How to force a static member to be initialized?
How to automatically register a class on creation

I have a class which should register her create method in a Factory such that I can create this class by using the factory. However the initialisation only works if I instantiate the class in the main method.

Here the class which I want to register:

class CDESolverD2Q5 : public CDESolver
{
public:

    static CDESolver* create()
    {
        return new CDESolverD2Q5;
    }
private:
    static const std::string name_;
    /**
     * @brief registered_ if true then class is registered w/ Solver Factory
     */
//only for accessing this element from the main method
public:
    static const bool registered_;
    /**
     * @brief registerLoader Registers the Solver with the factory.
     * @return A boolean that indicates if the registration was successful
     */
    static bool registerLoader();

};

And here the code in the cpp file:

const std::string CDESolverD2Q5::name_ = "CDESolverD2Q5";


bool CDESolverD2Q5::registerLoader()
{
    return SolverFactory.registerType(CDESolverD2Q5::name_, CDESolverD2Q5::create);
}

const bool CDESolverD2Q5::registered_ = CDESolverD2Q5::registerLoader();

And here the registerType method of my factory:

bool registerType(const IdentifierType& id,
                      ProductCreatorSignature creator)
    {
        return productMap_.insert(typename ProductMap::value_type(id, creator)).second;
    }

However the static member is only initialised if I access it in the main method:

int main(int argc, char* argv[]) {
    //how can I avoid the next line?
    bool blub = CDESolverD2Q5::registered_;

    CdeSolver* solver =SolverFactory.createObject("CDESolverD2Q5");
}

If I remove the line bool blub = CDESolverD2Q5::registered_; The class is not registered in my factory. But I thought that static members a initialised automatically before the main method is executed, then why do I need this line and how could I avoid this line?

Cœur
  • 37,241
  • 25
  • 195
  • 267
tune2fs
  • 7,605
  • 5
  • 41
  • 57

0 Answers0