如何使用std :: stoi创建std :: function作为方法参数作为默认值?

Kev*_*ARD 6 c++ function std c++11

我想使用an std::function作为方法的参数并将其默认值设置为std::stoi.

我尝试了以下代码:

void test(std::function<int(const std::string& str, size_t *pos , int base)> inFunc=std::stoi)
Run Code Online (Sandbox Code Playgroud)

不幸的是我收到以下错误:

no viable conversion from '<overloaded function type>' to 'std::function<int (const std::string &, size_t *, int)>'
Run Code Online (Sandbox Code Playgroud)

我设法通过添加创建专用方法进行编译.

#include <functional>
#include <string>


int my_stoi(const std::string& s)
{
    return std::stoi(s);
}

void test(std::function<int(const std::string&)> inFunc=my_stoi);
Run Code Online (Sandbox Code Playgroud)

第一个版本有什么问题?是不是可以使用std::stoi默认值?

Mik*_*our 12

第一个版本有什么问题?

stoifor string和for 有两个重载wstring.不幸的是,在获取指向函数的指针时,没有方便的方法来区分它们.

是不是可以使用std :: stoi作为默认值?

您可以转换为所需的重载类型:

void test(std::function<int(const std::string&)> inFunc =
    static_cast<int(*)(const std::string&,size_t*,int)>(std::stoi));
Run Code Online (Sandbox Code Playgroud)

或者你可以将它包装在lambda中,这类似于你所做的但没有引入不需要的函数名:

void test(std::function<int(const std::string&)> inFunc =
    [](const std::string& s){return std::stoi(s);});
Run Code Online (Sandbox Code Playgroud)

  • @CharlesPehlivanian:因为只有一个重载可以转换为该函数类型(这就是我的示例中的强制转换工作原因).两者都可以是`std :: function`的模板构造函数的参数,并且不允许编译器实例化两个模板特化以查看哪个可能有效. (2认同)