Reputation: 190799
This post taught me how to initialize static std::map.
I could use this method to initialize a static map from int to STRUCTURE.
The code is as follows
#include <string>
#include <map>
#include <iostream>
typedef unsigned long GUID;
enum Function {
ADDER = 1,
SUBTRACTOR = 2,
MULTIPLIER = 3,
SQUAREROOT = 4
};
struct PluginInfo
{
GUID guid;
std::string name;
Function function;
PluginInfo(GUID guid, std::string name, Function function) : guid(guid), name(name), function(function) {}
PluginInfo() {}
};
typedef std::map<GUID, PluginInfo> PluginDB;
PluginInfo temp1(1, "Adder", ADDER);
PluginInfo temp2(2, "Multiplier", MULTIPLIER);
PluginDB::value_type pluginDbArray[] = {
PluginDB::value_type(1, temp1),
PluginDB::value_type(2, temp2)
};
const int numElems = sizeof pluginDbArray / sizeof pluginDbArray[0];
PluginDB pluginDB(pluginDbArray, pluginDbArray + numElems);
int main()
{
std::cout << pluginDB[1].name << std::endl;
}
Can I simplify the initialization code?
PluginDB::value_type pluginDbArray[] = {
PluginDB::value_type(1, temp1),
PluginDB::value_type(2, temp2)
};
I tried
PluginDB::value_type pluginDbArray[] = {
PluginDB::value_type(1, {1, "Adder", ADDER}),
PluginDB::value_type(2, {2, "Multiplier", MULIPILER})
};
However, I got error messages
mockup_api.cpp:24: error: expected primary-expression before ‘(’ token
mockup_api.cpp:24: error: expected primary-expression before ‘{’ token
I guess I can make the structure to contain only the data if this is possible.
struct PluginInfo
{
GUID guid;
std::string name;
Function function;
}
Upvotes: 0
Views: 3016
Reputation: 168626
I'd use Boost.Assignment :
#include <boost/assign/list_of.hpp>
...
/* no more temp1, temp2, or PluginDbArray */
...
PluginDB pluginDB = boost::assign::map_list_of
(1, PluginInfo(1, "Adder", ADDER))
(2, PluginInfo(2, "Multiplier", MULTIPLIER));
Upvotes: 1
Reputation: 96241
You can't do that in C++98/03. You may be able to do it with compound initializers in C++0x.
I think you can do this which may be good enough in C++98 though:
PluginDB::value_type pluginDbArray[] = {
PluginDB::value_type(1, PluginInfo(1, "Adder", ADDER)),
PluginDB::value_type(2, PluginInfo(2, "Multiplier", MULTIPLIER))
};
Upvotes: 4