Reputation: 3
I am trying to create a C++ map with following template
map<string,class> mapper;
where mapper will contain following data
mapper['a'] = Class A or object of Class A
mapper['b'] = Class B or object of Class B
mapper['c'] = Class C or object of Class C
What should be the template of the mapper for this kind of map where Class is selected based on the input string?
Upvotes: 0
Views: 398
Reputation: 93264
Assuming that the strings are only known at run-time and that you can build an hierarchy of classes, the easiest option is using polymorphism and std::function
in order to build a map of factory functions:
Given...
struct Base
{
virtual ~Base() { }
};
struct Derived0 : Base { };
struct Derived1 : Base { };
// ...
...you can have...
std::map<std::string, std::function<std::unique_ptr<Base>>> map;
map["derived0"] = []{ return std::make_unique<Derived0>(); };
map["derived1"] = []{ return std::make_unique<Derived1>(); };
// ...
...which can be used as follows:
std::string desiredType;
std::cin >> desiredType;
auto result = map[desiredType]();
Note that this kind of design usually is a code smell. Think carefully about what you want to achieve - there probably is a cleaner/more elegant way of doing it.
Also, using std::unique_ptr
and std::function
may introduce noticeable overhead in your application.
Upvotes: 1