将重载函数(如std :: stoll)打包到std :: function中

Wal*_*ter 2 c++ overloading c++11 std-function

我很难打包std::stoll成一个std::function.天真

std::function<std::int64_t(std::string const&)> obj = std::stoll;
Run Code Online (Sandbox Code Playgroud)

失败,因为std::stoll是两个函数的重载(cppreference没有提到[在询问的时候]),一个将std::string另一个std::wstring作为第一个参数.那么我怎么得到我想要的东西?

我知道我可以使用lambda来调用std::stoll,但我正在寻找表单的解决方案

auto parser = ???
std::function<std::int64_t(std::string const&)> obj{parser};
Run Code Online (Sandbox Code Playgroud)

Joh*_*nck 6

您可以强制转换函数指针以消除歧义:

function<int64_t(string const&)> obj =
  static_cast<int64_t(*)(string const&)>(stoll);
Run Code Online (Sandbox Code Playgroud)

编辑:你还需要绑定默认参数,因为它stoll是一个三参数函数,你试图让它只需要一个参数:

function<int64_t(string const&)> obj =
  std::bind(static_cast<int64_t(*)(string const&, size_t*, int)>(stoll),
    placeholders::_1, nullptr, 10);
Run Code Online (Sandbox Code Playgroud)