Reputation: 2218
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?
Upvotes: 6
Views: 1919
Reputation: 254691
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);});
Upvotes: 12