简体   繁体   中英

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 .

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?

What's wrong in the first version?

There are two overloads of stoi , for string and wstring . 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?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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