Python to c++ conversion problem

A

Akdes Serin

I have a code in python like
if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom
function takes Direction enum as a parameter

When I am trying to write this code in c++
if (player->moveRoom(s[1])) //s[1] is a string so it outputs an error
because of not taking enum as a parameter

How can I change string to enum in c++?
Thanks.
 
A

Ahmed MOHAMED ALI

Hi,
Convert the string to int then cast the int to enum with static_cast.
Ahmed
 
I

Ivan Vecerina

Akdes Serin said:
I have a code in python like
if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom
function takes Direction enum as a parameter

When I am trying to write this code in c++
if (player->moveRoom(s[1])) //s[1] is a string so it outputs an error
because of not taking enum as a parameter

How can I change string to enum in c++?
Obviously C++ has no eval equivalent, but it also has limited
"introspection" at run-time. That is, the executing code has
no way to know the compile-time name associated with the enum
values.

One way to do this mapping manually would be:

#include <map>
#include <string>

enum ERoom
{ roomEntrance = 0
, roomLobby = 1
, roomCave = 2
};
typedef std::map<std::string,ERoom> RoomLookup;
typedef RoomLookup::value_type RoomLookupEntry;
RoomLookupEntry roomLookupData[3] =
{ RoomLookupEntry("Entrance", roomEntrance )
, RoomLookupEntry("Lobby", roomLobby )
, RoomLookupEntry("Entrance", roomCave )
};
RoomLookup sRoomLookup(roomLookupData,roomLookupData+3);

Then in your code:
if (player->moveRoom(sRoomLookup[ s[1] ]))

An annoyance with this approach is that your are writing
everything twice.
There are tricks to avoid that, using the preprocessor,
but it has its own drawbacks (see the thread associated with
http://groups.google.ca/[email protected] )

But for a game, most typically, the code would load
room descriptions from a data file at run-time, and
dynamically generate the equivalent of sRoomLookup.


I hope this helps,
Ivan
 
J

Jerry Coffin

Akdes said:
I have a code in python like
if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom
function takes Direction enum as a parameter

When I am trying to write this code in c++
if (player->moveRoom(s[1])) //s[1] is a string so it outputs an error
because of not taking enum as a parameter

How can I change string to enum in c++?

The most obvious way would be to use an std::map of strings and the
enum that's equivalent to each.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top