Runtime Function Specifications Based on User Input [closed] - c++

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Ok, so it's been a while since I wrote anything big in c++ and I've grown used to some of the niceties of more modern languages. This is one that's been nagging at me and I'm sure there's an answer out there. Is there any way to call a function specified as a string by a user at run-time? Without having to resort to some sort of massive switch/if block?
The situation I'm in boils down to this: I've got a whole whack-load of math-related problems I've solved in C++ and specified as "Problem1.cpp/Problem1.h", "Problem2.cpp/Problem2.h", etc. Each problem has a function called problemX() (where X is the number of the problem) that kicks off the solution.
At the start of the program I'd like to ask the user "Which problem would you like to solve?" and they'd specify a number. I'd then like to call the appropriate problemX() function without having to resort a massive hard coded switch statement (or an if statement, or an indexed array of function pointers, etc).
I'm sure this has got to be possible, but I just can't remember how to go about it. Any ideas?

unordered_map of strings to function pointers.
Tweak the user input to ensure it is all lower case (or upper IF YOU LIKE SHOUTING), then just lookup the function. If it exists call it, else error.

C++ has no automatic compile or run time reflection of its code in the language. Many library frameworks do have run time reflection of the symbols in a library.
So solution 1:
Stick your problems into their own dynamic libraries, and have the main program dynamically load them and look up the symbol names they export.
Solution 2:
Replace your raw C-style functions with named objects. So you might have:
class Problem;
void RegisterProblem( std::string name, Problem const* problem );
std::map< std::string, Problem const* >& GetProblems();
class Problem
{
protected:
Problem( std::string name ): RegisterProblem( std::move(name), this ) {}
virtual void operator() const = 0;
virtual ~Problem() {}
};
class Problem1: public Problem
{
public:
Problem1():Problem("Problem1") {}
virtual void operator() const { /* implementation */ }
};
// in .cpp file:
Problem1 problem1Instance();
void RegisterProblem( std::string name, Problem const* problem )
{
GetProblems()[name] = problem;
}
std::map< std::string, Problem const* >& GetProblems()
{
static std::map< std::string, Problem const* > problemMap;
return problemMap;
}
int main()
{
// parse user input to get this string:
std::string testInput = "Problem1";
// run the problem determined by testInput:
Problem* prob = GetProblems()[testInput];
Assert(prob);
(*prob)();
}
Above we have some horribly written spew of code that has self-registering Problems (who register in a static map), and a main() that executes whatever problem the string specifies.
A way I think would be cleaner is:
// In RegisterProblem.h:
// these two have obvious implementations:
std::map< std::string, std::function<void()> >& GetProblems();
bool RegisterProblem( std::string s, std::function<void()> ); // always returns true
// In problem1.cpp:
void Problem1(); // implement this!
bool bProblem1Registered = RegisterProblem( "Problem1", Problem1 );
// In problem2.cpp:
void Problem2(); // implement this!
bool bProblem2Registered = RegisterProblem( "Problem2", Problem2 );
// etc
// in main.cpp:
int main(int argc, char** argv)
{
if (argc == 0)
return -1; // and maybe print help
auto it = GetProblems().find( argv[1] );
if (it == GetProblems().end())
return -1; // and maybe print help
it->second(); // call the problem
}
where we do away with the needless class hierarchy and just maintain a map between string and void() functions. The maintenance of this map is distributed to each place where the functions are written, so there is no central list or if statement.
I wouldn't ship anything with code as crude as the above, but I hope you get the idea.

You should use an std::map<std::string,_function_pointer_defined_by_you> to store the names of the functions as keys, and the function pointers as values. You could also use an std::unordered_map<std::string,_function_pointer_defined_by_you>, which is something like std::hash_map. If you can use C++11, you will find the std::unordered_map at the header file <unordered_map>, and if you can't at <tr1/unordered_map>. Documentation about both map, and unordered_map can be found at:
http://cplusplus.com/reference/stl/map/
http://cplusplus.com/reference/stl/unordered_map/

Related

prevent string literals from being converted to bool versus std::string

Similar questions have been asked before, such as String literal matches bool overload instead of std::string.
But what I want to know is what should C++ developers do to prevent this from happening? As someone who writes C++ libraries for others to consume, what should I do to ensure this doesn't happen? Here is the example I ran into today, where a library had 2 initialize() methods:
void initialize(bool someflag) { /* ... */ }
void initialize(const std::string & name) { /* ... */ }
Now the problematic code was in the application that wanted to utilize this functionality and which called it in a manner similar to this:
initialize("robert");
At first glance you'd think that this would call initialize(string) but it actually calls the first initialize(bool) with a boolean flag set to true!
Yes, I know it can be fixed with this:
initialize( std::string("robert") );
But this puts the onus on the caller.
Edit for #zdan: I didn't consider the "solutions" in the other linked question to be great solutions since 1) I was hoping not to have to add a const char * version of every method that takes a bool or string, and 2) the template solution increases the maintainability of the code significantly for affected methods, renders them almost unreadable.
what should I do to ensure this doesn't happen?
One possibility is to create an overload that accepts a char const* and make it a pass through to the overload that accepts a std::string.
void initialize(char const* name) { initialize(std::string(name)); }

Converting input from std::cin to runnable code C++ [duplicate]

This question already has answers here:
Calling a Function From a String With the Function’s Name in C++
(8 answers)
Closed 7 years ago.
I'm working on a project and I need a way of receiving input from the console/user and use that to run a certain part in the code without the need of elaborate switch/if:else statements. Let me give you an example.
#include <iostream>
#include <string>
using namespace std;
void foo();
void foo2();
int main(){
string s;
cin >> s;
/*Take the input from cin and turn it into a function call, or some other
form of runnable code, like so*/
//Lets say the user inputs "run foo"
foo();
//Or if they input "run foo2"
foo2();
return 0;
}
void foo(){
cout << "Foo works, yay :D";
}
void foo2(){
cout << "Foo2 works, yay :D";
}
You might think I could do this with a switch or multiple if:else statements but this little code is just a small representation of what I need to do. The project requires this to be used on a large scale and I'd like it if I didn't need to use those, to save lines.
So is there any way I can do this in C++? Where the console user tells the program what to run and it runs said function?
Thanks!!
EDIT This is not a duplicate of the string to function call as this gets the input directly from the user versus from the program. As well as the answers show that you can use lua to do this since it is from user input.
Maybe the simplest thing would be to use a std::map of std::function objects:
std::map<std::string, std::function<void()>> funcs;
funcs[userInputString]();
Live example.
Depending on your requirements you may need something more sophisticated than this however and at some point of complexity you might want to consider embedding a scripting language like Lua.
Straight-forward way:
Make a map of string to std::function<void()>
Take the cin input string
Explode the string by spaces to a string array
If the first value is "run", Search the map for the second value and if you find it, execute the function pointer.
Arguments are hard to implement this way.
Better way:
Use LUA, Squirrel, Angel Code, JS, Python, or any other C/C++ embedded language available.
typedef void (*ScriptFunction)(void); // function pointer type
typedef std::map<std::string, ScriptFunction> script_map;
void some_function(void)
{
}
script_map m;
m.insert(std::make_pair("blah", &some_function));
void call_script(const std::string& pFunction)
{
script_map::const_iterator iter = m.find(pFunction);
if (iter == m.end())
{
// not found
}
(*iter->second)();
}
call call_script(user_input); in your code

create function signature that return both true and false while providing details upon failure [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The short version of this question is how to implement a single function that return both true and false while providing details upon failure (false)?
Say I want to create static function remove() that will get a path as a string and remove it from the file system.
Assuming remove operation may cause some unexpected errors, I'd like to be able to return a status.
Version 1
static bool remove( const string& path );
This will return true if path was removed and false otherwise.
But what if I need more details regarding the failure of the remove process?
Version 2
static void remove( const string& path );
This function now throw some exception on failure which will basically return the reason why remove process failed. This mandates each caller to use try-catch when calling this function which can be a bit annoying and ugly if you don't care about the result.
I trying to generate a clean signature that will allow me to combine both versions into a single one.
remove function is just one of many static utility functions so I'd like to avoid having to leave both versions (even though they are not overrideable at the moment).
Suggestion 1:
static bool remove( const string& path, bool throw_on_fail );
Now the caller can alternate both versions of the function by passing a boolean flag.
I don't like this suggestion. As I said remove function is just one of many static utility functions. I don't think adding boolean argument for each function is such a good idea.
Suggestion 2:
static EResultCode remove( const string& path );
Here we have an enum as the result.
This one is a bit better but I can already see such bugs as the next if statement if remove("f1"). getting int value 4 from remove() does not imply success.
Suggestion 3:
static Result remove( const string& path );
Here we have a class Result that will contain both Boolean and detailed description.
This seems like an overkill to me.
Question
I looked at the API of common c++ libraries interface, wx & boost. could not find overwhelming insights there.
I'm trying to come up with a generic signature for all those functions. which way would you go?
I would definitely go with the Result class approach.
Ignoring the question of whether exceptions are the right tool to handle a file-not-found error in the first place, an additional bool parameter to enable or disable them will make client code less readable because of all the true and false arguments whose meaning is completely unclear unless the reader consults remove()'s documentation or at least its signature:
remove("file.txt", true); // what's true?!
I would also refrain from error references. It is so frustrating when you (the function's client) are forced to use additional local variables which you might not even need later on. Very C++-unlike. This approach will eventually result in a lot of client code like this:
Error dummy;
remove("file.txt", dummy);
The Result class approach means clients will have to type a bit more if they need to know the details of an error, but their code will become much clearer and readable as a result of it. Your concern that this may put an additional burden on clients seems unfounded, at least if I imagine myself as the client of remove() :)
struct status {
std::string msg;
bool success;
status(): success(true) {}
status(std::string msg_): success(false), msg(msg_) {}
explicit operator bool() const { return success; }
};
static status const success;
status func1() { return true; }
status func2() { return success; }
status func3() { return status("something went wrong); }
if (func1()) { std::cout << "success!" << std::endl; }
if (func1().success) { std::cout << "success!" << std::endl; }
auto rc = func3();
if (!rc) { std::cout << "error" << rc.msg << std::endl; }
If you have a function remove(), and that functions purpose is to remove things from the file system, we should expect it to work in the normal case.
In the case where is can't work for some reason (there are a multitude of reasons it could fail) we should treat that as an exception to the normal working case.
I would suggest:
void remove() {...}
And calling it:
try
{
remove("/home/olduser");
}
catch(std::runtime_error& e)
{
std::cerr << "Failed to remove: " << e.what() << '\n';
}
Exceptions are part of the language for a reason, use them.
You said you looked to boost (and others) for inspiration. Look at the implementation of boost::asio. Almost all of the functions there have two overloads, one that takes an error code to report into, and one that has the same behavior but simply throws the error code as an exception in the case of failure.
Providing both may be overkill. My preference is to rely on exception handling, as it was specifically designed for handling these types of situations.
What I did in one case is have the function return a char
const*, with a nullptr for success, and the error message for
failure. Still, in this case, the functions were extern "C",
so I didn't have nearly as many alternatives. In C++, I'd
probably define a class, and return it. The class could have an
implicit conversion to bool if you wanted, but I'm not
convinced that it's a good idea; I'd have a succeeded function
which returned bool: it's a lot clearer.
Note that even in this case, you'll have to store the return
value into a local variable, in order to have the additional
information still present after you've detected the failure; you
cannot simply write:
if ( remove( path ) ) {
// error
} else {
// success
}
but need to write:
Results results = remove( path );
if ( !results ) {
// error, do something with results.message()
} else {
// success
}
Also rather painful, almost as much as a try catch.
You can use something like
static bool remove( const string& path, tStatus& myStatus );
And define tStatus as whatever type you want to return errors as. Could be as simple as typedef int tStatus;
You may use:
static bool remove(const string& path, std::nothrow_t);
static void remove(const string& path);
You could also let the function return a bool, and among the parameters you pass a reference to a structure that may contain the reason. Like this:
bool remove(const string& path, FailReason* fr){
//if the FailReason is a null pointer we don't fill it
If(fr != 0);
}
You can pass null in the fail struct

Several specific methods or one generic method?

this is my first question after long time checking on this marvelous webpage.
Probably my question is a little silly but I want to know others opinion about this. What is better, to create several specific methods or, on the other hand, only one generic method? Here is an example...
unsigned char *Method1(CommandTypeEnum command, ParamsCommand1Struct *params)
{
if(params == NULL) return NULL;
// Construct a string (command) with those specific params (params->element1, ...)
return buffer; // buffer is a member of the class
}
unsigned char *Method2(CommandTypeEnum command, ParamsCommand2Struct *params)
{
...
}
unsigned char *Method3(CommandTypeEnum command, ParamsCommand3Struct *params)
{
...
}
unsigned char *Method4(CommandTypeEnum command, ParamsCommand4Struct *params)
{
...
}
or
unsigned char *Method(CommandTypeEnum command, void *params)
{
switch(command)
{
case CMD_1:
{
if(params == NULL) return NULL;
ParamsCommand1Struct *value = (ParamsCommand1Struct *) params;
// Construct a string (command) with those specific params (params->element1, ...)
return buffer;
}
break;
// ...
default:
break;
}
}
The main thing I do not really like of the latter option is this,
ParamsCommand1Struct *value = (ParamsCommand1Struct *) params;
because "params" could not be a pointer to "ParamsCommand1Struct" but a pointer to "ParamsCommand2Struct" or someone else.
I really appreciate your opinions!
General Answer
In Writing Solid Code, Steve Macguire's advice is to prefer distinct functions (methods) for specific situations. The reason is that you can assert conditions that are relevant to the specific case, and you can more easily debug because you have more context.
An interesting example is the standard C run-time's functions for dynamic memory allocation. Most of it is redundant, as realloc can actually do (almost) everything you need. If you have realloc, you don't need malloc or free. But when you have such a general function, used for several different types of operations, it's hard to add useful assertions and it's harder to write unit tests, and it's harder to see what's happening when debugging. Macquire takes it a step farther and suggests that, not only should realloc just do _re_allocation, but it should probably be two distinct functions: one for growing a block and one for shrinking a block.
While I generally agree with his logic, sometimes there are practical advantages to having one general purpose method (often when operations is highly data-driven). So I usually decide on a case by case basis, with a bias toward creating very specific methods rather than overly general purpose ones.
Specific Answer
In your case, I think you need to find a way to factor out the common code from the specifics. The switch is often a signal that you should be using a small class hierarchy with virtual functions.
If you like the single method approach, then it probably should be just a dispatcher to the more specific methods. In other words, each of those cases in the switch statement simply call the appropriate Method1, Method2, etc. If you want the user to see only the general purpose method, then you can make the specific implementations private methods.
Generally, it's better to offer separate functions, because they by their prototype names and arguments communicate directly and visibly to the user that which is available; this also leads to more straightforward documentation.
The one time I use a multi-purpose function is for something like a query() function, where a number of minor query functions, rather than leading to a proliferation of functions, are bundled into one, with a generic input and output void pointer.
In general, think about what you're trying to communicate to the API user by the API prototypes themselves; a clear sense of what the API can do. He doesn't need excessive minutae; he does need to know the core functions which are the entire point of having the API in the first place.
First off, you need to decide which language you are using. Tagging the question with both C and C++ here makes no sense. I am assuming C++.
If you can create a generic function then of course that is preferable (why would you prefer multiple, redundant functions?) The question is; can you? However, you seem to be unaware of templates. We need to see what you have omitted here to tell if you if templates are suitable however:
// Construct a string (command) with those specific params (params->element1, ...)
In the general case, assuming templates are appropriate, all of that turns into:
template <typename T>
unsigned char *Method(CommandTypeEnum command, T *params) {
// more here
}
On a side note, how is buffer declared? Are you returning a pointer to dynamically allocated memory? Prefer RAII type objects and avoid dynamically allocating memory like that if so.
If you are using C++ then I would avoid using void* as you don't really need to. There is nothing wrong with having multiple methods. Note that you don't actually have to rename the function in your first set of examples - you can just overload a function using different parameters so that there is a separate function signature for each type. Ultimately, this kind of question is very subjective and there are a number of ways of doing things. Looking at your functions of the first type, you would perhaps be well served by looking into the use of templated functions
You could create a struct. That's what I use to handle console commands.
typedef int (* pFunPrintf)(const char*,...);
typedef void (CommandClass::*pKeyFunc)(char *,pFunPrintf);
struct KeyCommand
{
const char * cmd;
unsigned char cmdLen;
pKeyFunc pfun;
const char * Note;
long ID;
};
#define CMD_FORMAT(a) a,(sizeof(a)-1)
static KeyCommand Commands[]=
{
{CMD_FORMAT("one"), &CommandClass::CommandOne, "String Parameter",0},
{CMD_FORMAT("two"), &CommandClass::CommandTwo, "String Parameter",1},
{CMD_FORMAT("three"), &CommandClass::CommandThree, "String Parameter",2},
{CMD_FORMAT("four"), &CommandClass::CommandFour, "String Parameter",3},
};
#define AllCommands sizeof(Commands)/sizeof(KeyCommand)
And the Parser function
void CommandClass::ParseCmd( char* Argcommand )
{
unsigned int x;
for ( x=0;x<AllCommands;x++)
{
if(!memcmp(Commands[x].cmd,Argcommand,Commands[x].cmdLen ))
{
(this->*Commands[x].pfun)(&Argcommand[Commands[x].cmdLen],&::printf);
break;
}
}
if(x==AllCommands)
{
// Unknown command
}
}
I use a thread safe printf pPrintf, so ignore it.
I don't really know what you want to do, but in C++ you probably should derive multiple classes from a Formatter Base class like this:
class Formatter
{
virtual void Format(unsigned char* buffer, Command command) const = 0;
};
class YourClass
{
public:
void Method(Command command, const Formatter& formatter)
{
formatter.Format(buffer, command);
}
private:
unsigned char* buffer_;
};
int main()
{
//
Params1Formatter formatter(/*...*/);
YourClass yourObject;
yourObject.Method(CommandA, formatter);
// ...
}
This removes the resposibility to handle all that params stuff from your class and makes it closed for changes. If there will be new commands or parameters during further development you don't have to modifiy (and eventually break) existing code but add new classes that implement the new stuff.
While not full answer this should guide you in correct direction: ONE FUNCTION ONE RESPONSIBILITY. Prefer the code where it is responsible for one thing only and does it well. The code whith huge switch statement (which is not bad by itself) where you need cast void * to some other type is a smell.
By the way I hope you do realise that according to standard you can only cast from void * to <type> * only when the original cast was exactly from <type> * to void *.

c++ std::map of heterogeneous function pointers

Is it possible to store pointers to various heterogenous functions like:
In the header:
int functionA (int param1);
void functionB (void);
Basically this would the part I don't know how to write:
typedef ??boost::function<void(void)>?? functionPointer;
And afterwards:
map<char*,functionPointer> _myMap;
In the .cpp
void CreateFunctionMap()
{
_myMap["functionA"] = &functionA;
_myMap["functionB"] = &functionB;
...
}
And then reuse it like:
void execute(int argc, char* argv[])
{
if(argc>1){
int param = atoi(argv[1]);
int answer;
functionPointer mfp;
mfp = map[argv[0]];
answer = *mfp(param);
}
else{
*map[argv[0]];
}
}
etc.
Thanks
--EDIT--
Just to give more info:
The reason for this question is that I am implementing a drop-down "quake-style" console for an already existing application. This way I can provide runtime command line user input to access various already coded functions of various types i.e.:
/exec <functionName> <param1> <param2> ...
If you want to have "pointer to something, but I'm not going to define what, and it could be a variety of things anyway" you can use void *.
But you really shouldn't.
void * is purely a pointer. In order to do anything with it, you have to cast it to a more meaningful pointer, but at that point, you've lost all type safety. What's to stop someone from using the wrong function signature? Or using a pointer to a struct?
EDIT
To give you a more useful answer, there's no need to put this all into a single map. It's ok to use multiple maps. I.e.
typedef boost::function<void(void)> voidFunctionPointer;
typedef boost::function<int(int)> intFunctionPointer;
map<std::string, voidFunctionPointer> _myVoidMap;
map<std::string, intFunctionPointer > _myIntMap;
void CreateFunctionMap()
{
_myVoidMap["functionA"] = &functionA;
_myIntMap["functionB"] = &functionB;
...
}
void execute(int argc, char* argv[])
{
if(argc>1){
int param = atoi(argv[1]);
int answer;
// todo: check that argv[0] is actually in the map
intFunctionPointer mfp = _myIntMap[argv[0]];
answer = mfp(param);
}
else{
// todo: check that argv[0] is actually in the map
voidFunctionPointer mfp = _myVoidMap[argv[0]];
mfp();
}
}
You can use
boost::variant<
boost::function<void(void)>,
boost::function<void(int)> >
Why not just add functions of type int (*func)(int argc, char* argv[])? You could easily remove first arg from execute's params and call the relevant one.
Can you not use the command pattern to encapsulate the function calls. So you can store the functions in functors and call them after wards. For functor implementation you can have a look at Modern C++ Design by Andrei Alexandrescu.
Each of your functions has a different type, so you need some kind of type erasure. You could use the most generic of them: Boost.Any. You can have a map of boost::any, but you need to know the type of the function in order to get it back and call it.
Alternatively, if you know your arguments ahead of time you can bind them with the function call and have all functions in the map be nullary functions: function< void() >. Even if you don't, you may be able to get away with it by binding the argument to references, and then at call time fill the referred variables with the appropiate arguments.