JAN
JAN

Reputation: 21865

Too much classes with the same concept

I have 5 classes that are used as operators :

TurnOn , TurnOff , PushBox , Exit , Enter

And I have for each type , a string that holds a description of that type .

For instance :

class Places {

enum Type { Room1 ,Room2 ,Room3 ,Room4 };


// more stuff

};
TurnOn turnOn(Places::Room1);
string turnOnString = "TurnOn(Room1)" ;

I want to store the info in a map , so I have 5 maps for each operator :

map <string , TurnOn > opeatorTurnOn;
map <string , TurnOff > opeatorTurnOff ;
map <string , PushBox > opeatorTPushBox ;
map <string , Exit > opeatorExit ;
map <string , Enter > opeatorEnter ;

But now I have 5 maps with the same concept : a string with its operator .

How can I store the operators in one map so I won't have to hold 5 maps with the same concept ?

Upvotes: 2

Views: 147

Answers (4)

KillianDS
KillianDS

Reputation: 17176

It depends on how your operator classes are implemented (we have very little information), but I'd make a map of callables, something similar to this:

#include <iostream>
#include <functional>
#include <map>

struct op1
{
    void operator()(int i) { std::cout << "op1::operator() " << i << "\n"; }
};

struct op2
{
    void operator()(int i) { std::cout << "op2::operator() " << i << "\n"; }
};

int main()
{
    std::map<std::string, std::function<void(int)>> ops;
    ops["1"] = op1{};
    ops["2"] = op2{};
    ops["1"](42);
    ops["2"](42);
}

You could also always wrap the ops in lambdas if you don't use the operator() overloading.

Upvotes: 3

Aeluned
Aeluned

Reputation: 789

You can't store heterogeneous data types in a map (or any other STL container for that matter).

The simplest fix is to subclass them all off of one base class and store the base class in your map.

EDIT: I didn't notice the desire to avoiding polymorphism (though, I really don't understand why). In any case, I think boost::any or boost::variant might help you. You can store them all as a boost::any. http://www.boost.org/doc/libs/1_52_0/doc/html/any.html

Upvotes: 1

Puppy
Puppy

Reputation: 146910

boost::variant is usually used for such things.

Upvotes: 0

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

Make them all inherit from one base class, store pointer to base and use polymorphism.

Upvotes: 2

Related Questions