c++ - Return specific map entry instead of map::end if no map entry was found -


in switch statement, can specify default return value if none of other cases apply. i'd similar std::map, i'm not sure if possible: can make map return specific value/entry instead of map::end if no key fits search?

example (here i'd ultimatively - aware code doesn't work):

std::map<std::string, void* (*) (dataobject*)> commands; //mapping functions keys commands["test"] = function(dataobject d){dosomething();} commands[nothing else applies] = function(dataobject d){dosomethingelse();}  commands.find("test")(somedataobject); // dosomething(); happens commands.find("blabla")(somedataobject); //dosomethingelse(); happens because no other entry found 

would possible?

(also, way i'm using function pointers in example doesn't work @ - can use cpp11's lambda expressions accomplish want do?)

i not want use switch clause, nor want if(m.find(x) != m.end()) clause, nor want more if-else's.

you can use own functor default value:

struct myfunctor: public std::function<void(dataobject*)> {      template <typename f>     myfunctor (f &&f) : std::function<void(dataobject*)> (std::forward<f> (f)) { }      myfunctor () : std::function<void(dataobject*)> (dosomethingelse) { }  }; 

assuming dosomethingelse defined function.

then can do:

std::map<std::string, myfunctor> commands; //mapping functions keys commands["test"] = [] (dataobject *) { }; // assign lambda  dataobject *mydataobject= new dataobject(); commands["not defined"] (mydataobject); // call dosomethingelse 

you can have different default values (defined @ compile time) using template myfunctor:

template <void (*defaultfn) (dataobject*)> struct myfunctor: public std::function<void(dataobject*)> {      template <typename f>     myfunctor (f &&f) : std::function<void(dataobject*)> (std::forward<f> (f)) { }      myfunctor () : std::function<void(dataobject*)> (defaultfn) { }  };  std::map<std::string, myfunctor<dosomethingelse>> commands; 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -