std::ptr_fun replacement for c++17

和自甴很熟 提交于 2019-12-03 09:36:10

问题


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?


回答1:


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.




回答2:


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.




回答3:


According to cppreference, std::ptr_fun is deprecated since C++11 and discontinued since C++17.

Similarly, std::not1 is deprecated since C++17.

So best don't use either, but a lambda (as explained in other answers).




回答4:


Alternatively, you might use std::not_fn:

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



回答5:


My answer is similar to the Barry's answer (https://stackoverflow.com/a/44973511/1016580).

Instead of

int isspace(int c);

function from the standard C library, you can use

bool isspace(char c, const locale& loc);

function instantiation from the standard C++ library (http://en.cppreference.com/w/cpp/locale/isspace), which is more type-correct. In this case you don't need to think about char -> unsigned char -> int conversions and about the current user's locale.

The resulting lambda looks like this then:

[](char c) { return !std::isspace(c, std::locale::classic()); }


来源:https://stackoverflow.com/questions/44973435/stdptr-fun-replacement-for-c17

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!