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

标签 c++ function c++11 std

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

我尝试了以下代码:

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

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

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

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

#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);

第一个版本有什么问题? 难道不能使用 std::stoi 作为默认值吗?

最佳答案

What's wrong in the first version?

stoi 有两个重载,用于stringwstring。不幸的是,在获取指向函数的指针时,没有方便的方法来区分它们。

Isn't it possible to use std::stoi as default value?

您可以转换为您想要的重载类型:

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

或者您可以将其包装在 lambda 中,这与您所做的类似但不会引入不需要的函数名称:

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

关于c++ - 如何使用 std::stoi 作为默认值创建 std::function 作为方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20635630/

相关文章:

javascript - 使用文字点符号 setter 将属性注入(inject) ReactJS 功能组件是一种好习惯吗?

javascript - 如何在.load()之后获取javascript函数的返回值?

c++ - 对象构造 : default parameter vs delegation

c++ - 如果 std::string 从未修改过,它可以在创建后移动吗?

c++ - 如何有一个 vector 的复制构造函数?

Javascript onchange 不会多次更改

c++ - 仅当模板参数中存在 typedef 时才创建 typedef

c++ - 按节点计算单链表中的出现次数

c++ - 无法将 int 转换为 int[][]

c++ - STL 是否首先设置相等运算符检查大小?