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 Is stoi() in C++? In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings.
std::stoi Function in C++ The stoi() is a standard library function that turns a string into an integer. C++ programmers utilize the function, which stands for “string to integer,” to obtain integers from strings. Additionally, the stoi() function can remove other components, such as trailing letters from the string.
First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.
std::stoi is actually declared in <string> .
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);});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With