How to store functional objects with different signatures in a container?

后端 未结 5 1566
抹茶落季
抹茶落季 2020-11-27 23:40

So imagine we had 2 functions (void : ( void ) ) and (std::string : (int, std::string)) and we could have 10 more. All (or some of them) take in di

5条回答
  •  情话喂你
    2020-11-28 00:28

    You can use boost::any...

    #include 
    #include 
    #include 
    #include 
    
    void voidFunc()
    {
        std::cout << "void called" << std::endl;
    }
    
    void stringFunc(std::string str)
    {
        std::cout << str << std::endl;
    }
    
    int main()
    {
        std::map funcs;
        funcs.insert(std::pair("voidFunc", &voidFunc));
        funcs.insert(std::pair("stringFunc", &stringFunc));
    
        boost::any_cast(funcs["voidFunc"])();
        boost::any_cast(funcs["stringFunc"])("hello");
        return 0;
    }
    

    Note that you will get a runtime exception if you don't specify the function signature correctly in the any_cast.

提交回复
热议问题