1

I'm trying to make a class that can hold and later call functions. It stores the functions in a map along with a string that holds the name of the function.

I tried doing this on Linux with GCC and got the following error: "invalid conversion from void(*)() to void *" on the line functionsMap[nameOfFunction] = func;

Here's the entire program I have so far. It's not done yet, but I'm really curious as to why this would compile under Visual C++ and not GCC. If I'm doing something wrong or could be doing something better, please let me know. Thanks!

#include <iostream>
#include <map>
#include <string>
using namespace std; 

class Dyn_Class{
private: 
    map<string, void *> functionsMap; 

public: 
    Dyn_Class(){} 

    template<typename ReturnValue>
    void add_func( string nameOfFunction, ReturnValue(*func)() ){
        functionsMap[nameOfFunction] = func; 
    }

    void remove_func( string nameOfFunction ){

    }

    Dyn_Class operator()(string nameOfFunction){

    }
}; 

void print(void){
    for(int index = 0; index < 9; index++){
        cout << index << "   "; 
    }
    cout << endl; 
}

int main(){
    Dyn_Class functionsList; 

    functionsList.add_func("print", print); 

    return 0; 
}
4

3 回答 3

2

To have a map of pointers to function taking no arguments and returning void you need:

std::map<std::string, void(*)()> functionsMap; 

There is no point making add_func a template as it will only work when instantiated with ReturnValue = void (unless you add a potentially unsafe cast to its implementation).

If your code compiles with Visual C++ it is because Visual C++ is being permissive.

于 2012-05-14T20:48:51.047 回答
0

考虑使用 std::function 代替:

class Dyn_Class{
private: 
    map<string, function<void()> > functionsMap; 

public: 
    Dyn_Class(){} 

    template<typename FUNC>
    void add_func(const string& nameOfFunction, FUNC func){
        functionsMap.insert(make_pair(nameOfFunction, func));
    }

    void remove_func(const string& nameOfFunction ){

    }

    void operator()(const string& nameOfFunction){
        functionsMap[nameOfFunction]();
    }
}; 

好处?使用“函数”,您可以使用普通的旧函数指针,可以使用函子,也可以使用 lambda 表达式:

DynClass dyn;
dyn.add("print", []() { printf("Say hi"; } );
于 2012-05-14T22:58:49.697 回答
0

您可以将该函数作为参数传递,如下所示:

void add(void * f()){...}

如何在 C 中将函数作为参数传递?

于 2012-05-14T20:57:03.650 回答