Settings Array in C++
An associative data structure with varying data types is exactly what a struct
is...
struct SettingsType{ bool Fullscreen; int Width; int Height; std::string Title;} Settings = { true, 1680, 1050, "My Application" };
Now, maybe you want some sort of reflection because the field names will appear in a configuration file? Something like:
SettingsSerializer x[] = { { "Fullscreen", &SettingsType::Fullscreen }, { "Width", &SettingsType::Width }, { "Height", &SettingsType::Height }, { "Title", &Settings::Title } };
will get you there, as long as you give SettingsSerializer
an overloaded constructor with different behavior depending on the pointer-to-member type.
C++ is a strongly typed language. The containers hold exactly one type of object so by default what you are trying to do cannot be done with only standard C++.
On the other hand, you can use libraries like boost::variant or boost::any that provide types that can hold one of multiple (or any) type, and then use a container of that type in your application.
Rather than an array, you can use std::map
to map from the name of the setting to the value:
std::map<std::string, boost::variant<bool,int,std::string> >
#include <map>#include <string>std::map<std::string,std::string> settings;settings.insert("Fullscreen","true");settings.insert("Width","1680");settings.insert("Height","1050");settings.insert("Title","My Application");
Could be one way of doing it if you want to stick with the STL.