Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
Kevin MOLCARD Avatar asked Dec 17 '13 13:12

Kevin MOLCARD


People also ask

What is stoi () in C++?

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.

How does STD stoi work?

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.

What is the difference between Atoi and stoi?

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.

Where is stoi defined C++?

std::stoi is actually declared in <string> .


1 Answers

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);});
like image 117
Mike Seymour Avatar answered Sep 27 '22 16:09

Mike Seymour