Reputation: 143
I need to make following feature to my c++ programm:
When i run it, i type name of someone function, which i described in my program, and this function run. How to make it automatic? Not like my current code:
func1(){...}
func2(){...}
....
func50(){...}
int main(){
string function;
cin>>function;
if (function == "func1") funk1();
if (function == "func2") func2();
if (function == "func3") funk3();
....
return 0;
}
because i have many functions. Which instruments i could use?
Upvotes: 1
Views: 3642
Reputation: 6247
As mentioned in the other solutions one can use a map from function name to function pointer to get the function pointer. By the use of a macro one can come very close to what you intend (no need to manually fill the map). Finally your code will look similar to this:
DECLARE_FUNC(f1)
{
std::cout << "calling f1" << std::endl;
}
DECLARE_FUNC(f2)
{
std::cout << "calling f2" << std::endl;
}
// ... more functions
int main()
{
std::string function;
std::cin >> function;
TFunc f = s_funcs[function]; // get function pointer for name
if (f)
f();
// ...
To be able to do this you need the following definitions:
#include <map>
#include <string>
#include <iostream>
// the common type of all functions
typedef void (*TFunc)(void);
// a static map of name -> function
static std::map<std::string, TFunc> s_funcs;
// this class we need to statically add functions to the map
class FuncAdder
{
public:
FuncAdder(std::string name, TFunc f)
{
s_funcs[name] = f;
}
};
// finally the macro for declaring + adding + defining your function
#define DECLARE_FUNC(f) void f(); FuncAdder f##Adder(#f,f); void f()
Upvotes: 0
Reputation: 6914
In my opinion simplest way is to use std::map<std::string, std::function<...> >
and then create a global map from your functions and lookup on map:
typedef std::function<void()> my_function;
typedef std::map<std::string, my_function> functions_map;
void test1() {...}
void test2() {...}
void test3() {...}
#ifndef _countof
# define _countof(array) ( sizeof(array) / sizeof(array[0]) )
std::pair<std::string, my_function> pFunctions[] = {
std::make_pair( "test1", my_function(&test1) ),
std::make_pair( "test2", my_function(&test2) ),
std::make_pair( "test3", my_function(&test3) )
};
functions_map mapFunctions( pFunctions, pFunctions + _countof(pFunctions) );
void main() {
std::string fn;
while( std::cin >> fn ) {
auto i = mapFunctions.find( fn );
if( i != mapFunctions.end() )
i->second();
else
std::cout << "Invalid function name" << std::endl;
}
}
Upvotes: 0
Reputation: 258618
You can't make it completely automatic because C++ doesn't have reflection.
Any other automation you can cook up will basically be very similar to what you already have.
Some other options would be:
std::map
with the key a std::string
and the value a function pointer.std::string
.Upvotes: 4