加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何使用std :: stoi创建std :: function作为方法参数作为

发布时间:2020-12-16 05:19:07 所属栏目:百科 来源:网络整理
导读:我想使用std :: function作为方法的参数,并将其默认值设置为std :: stoi. 我尝试了以下代码: void test(std::functionint(const std::string str,size_t *pos,int base) inFunc=std::stoi) 不幸的是我收到以下错误: no viable conversion from 'overloaded
我想使用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?

对于字符串和wstring,有两个stoi重载.不幸的是,在获取指向函数的指针时,没有方便的方法来区分它们.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读