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

我想使用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);});

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...