在C++中设置数组

dan*_*jar 9 c++ arrays settings types

我的目标是设置一个数据结构来存储我的应用程序的设置.

在PHP中我会写...

$settings = array(
    "Fullscreen" => true,
    "Width"      => 1680,
    "Height"     => 1050,
    "Title"      => "My Application",
);
Run Code Online (Sandbox Code Playgroud)

现在我尝试在C++中创建一个类似的结构,但它还无法处理不同的数据类型.顺便说一句,如果有更好的方式存储这些设置数据,请告诉我.

struct Setting{ string Key, Value; };

Setting Settings[] = {
    ("Fullscreen", "true"),     // it's acceptable to store the boolean as string
    ("Width", "1680"),          // it's not for integers as I want to use them later
    ("Height", 1050),           // would be nice but of course an error
    ("Title", "My Application") // strings aren't the problem with this implementation
};
Run Code Online (Sandbox Code Playgroud)

我怎样才能的结构建模associative arrayflexible datatypes

Ben*_*igt 8

具有不同数据类型的关联数据结构正是如此struct......

struct SettingsType
{
    bool Fullscreen;
    int Width;
    int Height;
    std::string Title;
} Settings = { true, 1680, 1050, "My Application" };
Run Code Online (Sandbox Code Playgroud)

现在,也许您想要某种反射,因为字段名称将出现在配置文件中?就像是:

SettingsSerializer x[] = { { "Fullscreen", &SettingsType::Fullscreen },
                           { "Width",      &SettingsType::Width },
                           { "Height",     &SettingsType::Height },
                           { "Title",      &Settings::Title } };
Run Code Online (Sandbox Code Playgroud)

只要SettingsSerializer根据指向成员的指针类型给出一个具有不同行为的重载构造函数,它就会到达那里.

  • 这不是那么优雅,因为每次需要添加新设置类型时都需要更改此文件. (2认同)