Jump to content
  • Advertisement
Sign in to follow this  

How do i use the switch statement with std::string?

This topic is 4862 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Doesn't work. switch only works with integral numeric types, because of how it is compiled - it is not necessarily simply an if/else chain.

If you have only a few cases, just do if/else if/else as needed. If you have several, or if there will be a need to change the cases often in the design (or, as happens sometimes, dynamically at runtime, e.g. the strings in question are loaded from a file), you can build a std::map of std::strings to functors, and then look up the functor in the map and invoke it. (If the code for each case takes similar form, you may instead be able to make a map of std::string to some other sort of object, and then look up the object and pass it to some common processing function.

Something like:

#include <map>
#include <string>
using namespace std;
// ...

class Item() {
// whatever stuff in here
virtual Item* clone();

class Sword(): public Item {
// etc.
Sword* clone() { return new Sword(this) };
// need a proper copy ctor implementation

// etc. other classes

map<string, Item*> prototypes;
// populate map
prototypes["broadsword"] = new Sword(123, 456, 789);
// etc.
// Todo: somehow make use of a configuration file to do this.

// Create an item by cloning one of the 'prototypes'
Item * result = NULL;
map<string, Item*>::iterator it = prototypes.find(requestedItem);
if (requestedItem != prototypes.end()) {
result = it->second->clone();

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!