Wrap overloaded function via std::function

后端 未结 1 968
春和景丽
春和景丽 2020-12-03 09:07

I have an overloaded function which I want to pass along wrapped in a std::function. GCC4.6 does not find a \"matching function\". While I did find some questions here the a

相关标签:
1条回答
  • 2020-12-03 09:13

    That is ambiguous situation.

    To disambiguate it, use explicit cast as:

    typedef int (*funtype)(const std::string&);
    
    std::function<int(const std::string&)> func=static_cast<funtype>(test);//cast!
    

    Now the compiler would be able to disambiguate the situation, based on the type in the cast.

    Or, you can do this:

    typedef int (*funtype)(const std::string&);
    
    funtype fun = test; //no cast required now!
    std::function<int(const std::string&)> func = fun; //no cast!
    

    So why std::function<int(const std::string&)> does not work the way funtype fun = test works above?

    Well the answer is, because std::function can be initialized with any object, as its constructor is templatized which is independent of the template argument you passed to std::function.

    0 讨论(0)
提交回复
热议问题