正确执行全局配置

新手上路,请多包涵

我的目标是在我正在开发的 C++ 游戏中拥有全局常量(以表示一些图形信息等)。我目前的实现是将它们全部扔到一个 .h 中并将它们包含在任何地方。这行得通,除了每次我更改设置时,都必须重新编译整个代码库。

所以,我的下一个想法是将它们扔到一些配置 txt 文件中并解析它们,这样当设置更改时实际上不会更改任何代码。解析器很简单,我可以将值放入常量中,但是因为解析器是一个代码块,所以常量不再是全局的。

有没有解决这个问题的好方法?也许某种方式可以使它们成为全局,尽管它们处于一个块中,或者某种方式可以避免在更改设置时重新编译所有内容?

原文由 Cannoliopsida 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 700
2 个回答

另一种方法是创建一个单例类。

 #include <fstream>
#include <map>
#include <string>

class ConfigStore
{
public:
    static ConfigStore& get()
    {
        static ConfigStore instance;
        return instance;
    }
    void parseFile(std::ifstream& inStream);
    template<typename _T>
    _T getValue(std::string key);
private:
    ConfigStore(){};
    ConfigStore(const ConfigStore&);
    ConfigStore& operator=(const ConfigStore&);
    std::map<std::string,std::string> storedConfig;
};

这里配置保存在一个map中,也就是说只要parseFile可以读取文件,getValue可以解析类型,添加新key就不需要重新编译config类。

用法:

 std::ifstream input("somefile.txt");
ConfigStore::get().parseFile(input);
std::cout<<ConfigStore::get().getValue<std::string>(std::string("thing"))<<std::endl;

原文由 denahiro 发布,翻译遵循 CC BY-SA 3.0 许可协议

我用来解决这个问题的方法是将变量放在一个单独的全局命名空间中,该命名空间位于一个名为 config.h 的头文件中,然后将该文件包含在任何地方。

 // In config.h

#ifndef CONFIG_H
#define CONFIG_H

namespace config
{
    extern int some_config_int;
    extern std::string some_config_string;

    bool load_config_file();
}

#endif

然后在源文件中 定义 变量并将它们设置为默认值。此源文件还包含从配置文件加载变量的代码。

 // In config.cpp

namespace config
{
    int some_config_int = 123;
    std::string some_config_string = "foo";
}

bool config::load_config_file()
{
    // Code to load and set the configuration variables
}

现在,在每个源文件中,您都需要配置变量,包括 config.h 并像 config::some_config_int 一样访问它们。

但是,没有解决这个问题的“正确”方法,所有可行的方法在我看来都是正确的。

原文由 Some programmer dude 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题