在main()之前注册类/函数/东西

时间:2011-08-24 10:19:33

标签: c++

假设我有一个叫做诗的课。

class Poem{
   virtual void recite() = 0;
}

我有数百个.cpp和.hpp文件描述了一个子类,如下所示

class TheRaven : public Poem{
    void recite() { std::cout << "NEVERMORE!" << endl; }
}

喜欢。在main函数中,我希望能够遍历每个可能的Poem子类并调用它们的recite()函数。所以我上了课:

class PoemRegistry{
    std::map<std::string, Poem*> poems;
    PoemRegistry& getGlobal(); // returns a static global registry
    void register(const std::string& poemname, Poem * thepoem);
};

然后对于每个诗子类.cpp文件,我把以下内容。

class TheRavenRegistor{
    TheRavenRegistor(){
        PoemRegistry::getGlobal().register("theraven", new TheRaven());
    }
}
TheRavenRegistor registor();

忍者编辑:我把全球课放在那里,忘了它

轻松实现,我使用#define和模板创建了一个快捷方式。

现在,问题是,我刚刚听说过静态类初始化惨败。我想这会免疫它,或者我在这里肯定会遗漏一些东西?或者是否有更优雅的东西可以用于此目的?

1 个答案:

答案 0 :(得分:1)

这是 Singleton设计模式的示例。不要使用静态全局,因为初始化顺序在编译单元中是未定义的。 而是使用这样的东西:

PoemRegistry& PoemRegistry::getGlobal()
{
  static PoemRegistry theRegistry; // construction guaranteed when first call
  return theRegistry;
} 

制作getGlobal()方法static

class PoemRegistry
{
public:
  static PoemRegistry& getGlobal();
...