简体   繁体   English

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

[英]How to create an std::function as method argument with std::stoi as default value?

I would like to use an std::function as an argument of a method and set its default value as std::stoi . 我想使用std::function作为方法的参数,并将其默认值设置为std::stoi

I tried the following code: 我尝试了以下代码:

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

Unfortunately I get the following error: 不幸的是我收到以下错误:

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

I managed to compile by adding creating a dedicated method. 我设法通过添加创建专用方法进行编译。

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

What's wrong in the first version? 第一个版本有什么问题? Isn't it possible to use std::stoi as default value? 是不是可以使用std::stoi作为默认值?

What's wrong in the first version? 第一个版本有什么问题?

There are two overloads of stoi , for string and wstring . 对于stringwstring ,有两个stoi重载。 Unfortunately, there's no convenient way to differentiate between them when taking a pointer to the function. 不幸的是,在获取指向函数的指针时,没有方便的方法来区分它们。

Isn't it possible to use std::stoi as default value? 是不是可以使用std :: stoi作为默认值?

You could cast to the type of the overload you want: 您可以转换为所需的重载类型:

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

or you could wrap it in a lambda, which is similar to what you did but doesn't introduce an unwanted function name: 或者你可以将它包装在lambda中,这类似于你所做的但没有引入不需要的函数名称:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM