Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ptr_fun replacement for c++17

Tags:

c++

c++17

I am using std::ptr_fun as follows:

static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

as presented in this answer.

However this does not compile with C++17 (using Microsoft Visual Studio 2017), with the error:

error C2039: 'ptr_fun': is not a member of 'std'

How can this be fixed?

like image 545
user3717478 Avatar asked Jul 07 '17 14:07

user3717478


2 Answers

You use a lambda:

static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) {return !std::isspace(c);}));
    return s;
}

The answer you cited is from 2008, well before C++11 and lambdas existed.

like image 73
Nicol Bolas Avatar answered Nov 17 '22 20:11

Nicol Bolas


Just use a lambda:

[](unsigned char c){ return !std::isspace(c); }

Note that I changed the argument type to unsigned char, see the notes for std::isspace for why.

std::ptr_fun was deprecated in C++11, and will be removed completely in C++17.

like image 20
Barry Avatar answered Nov 17 '22 21:11

Barry