正确实施全局配置 [英] Proper implementation of global configuration

查看:68
本文介绍了正确实施全局配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在我正在开发的C ++游戏中使用全局常量(以表示一些图形信息等)。我目前的实施是将它们全部折合成.h,并将它们包括在内。这是有效的,除了每次我改变一个设置,整个代码库必须重新编译。



所以,我的下一个想法是折腾他们在一些配置txt文件和解析它们,这样在设置更改时实际上不会更改代码。解析器非常简单,我可以将这些值放入常量中,但由于解析器是一个代码块,常量不再是全局的。



是否有一个解决这个问题的好方法?也许某种方式可以让它们成为全局的,尽管它们处于阻止或某种方式来避免在更改设置时重新编译所有内容?解析方案

另一种方法要做到这一点将创建一个单身类。

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

class ConfigStore
{
public:
static ConfigStore& get()
{
静态ConfigStore实例;
返回实例;
}
void parseFile(std :: ifstream& inStream);
模板< typename _T>
_T getValue(std :: string key);
private:
ConfigStore(){};
ConfigStore(const ConfigStore&);
ConfigStore& operator =(const ConfigStore&);
std :: map< std :: string,std :: string> storedConfig;
};

这里的配置保存在地图中,这意味着只要parseFile可以读取文件,getValue就可以解析类型,如果添加新键,则不需要重新编译配置类。



用法:

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


My goal is to have global constants in a C++ game I'm working on (to represent some graphics info and the like). My current implementation is to toss them all in a .h and include them everywhere. This works, except that every time I change a setting, the entire code base must be recompiled.

So, my next idea was to toss them in some configuration txt file and parse them in, that way no code is actually changed when settings change. The parser was simple enough, and I could put the values into the constants, but because the parser was a code block, the constants were no longer global.

Is there a good way to solve this? Perhaps some way to make them global despite being in a block or some way to avoid recompiling everything when changing settings?

解决方案

Another way to do this would be to create a singleton class.

#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;
};

Here the configuration is saved in a map, meaning as long as parseFile can read the file and getValue can parse the type there is no need to recompile the config class if you add new keys.

Usage:

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

这篇关于正确实施全局配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆