Ptr_fun with lambda function

I have the following program that uses ptr_fun with a lambda function.

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>

using namespace std;
int main()
{
    string target="aa";
    vector<string> v1;
    v1.push_back("aa");
    v1.push_back("bb");
    auto stringcasecmp=[](string lhs, string rhs)->int
    {
        return strcasecmp(lhs.c_str(), rhs.c_str());
    };

    auto pos = find_if(
        v1.begin(), v1.end(),
        not1( bind2nd(ptr_fun(stringcasecmp), target) )
        );

    if ( pos != v1.end())
    cout <<   "The search for `" << target << "' was successful.\n"
        "The next string is: `" << pos[1] << "'.\n";
}

I get the following error messages.

stackoverflow.cpp: In function β€˜int main()’:
stackoverflow.cpp:21:41: error: no matching function for call to β€˜ptr_fun(main()::<lambda(std::string, std::string)>&)’
stackoverflow.cpp:22:6: error: unable to deduce β€˜auto’ from β€˜<expression error>’

How do I change the code (minimally) to compile it?

+5
source share
2 answers

bind2nd(Β§D.9) and ptr_fun(Β§D.8.2.1) are deprecated in C ++ 11. You can simply write another lambda function in find_if:

auto pos = find_if(v1.begin(), v1.end(),
                   [&](const std::string& s) {
                        return !stringcasecmp(s, target); 
                   });

ptr_fun(<lambda>)will not work, because it is ptr_fundesigned for C ++ 03 to convert a pointer to a function object for other adapters. Lambda is already a functional object, so ptr_funit is not required.

bind2nd , second_argument_type result_type, , bind2nd(<lambda>, target) . ++ 11 , :

std::bind(stringcasecmp, std::placeholders::_1, target)

bind ++ 03, not1: bind bind, .

std::not1(std::bind(stringcasecmp, std::placeholders::_1, target))

. - lambda, .

:

template <typename Predicate>
struct generic_negate
{
    explicit generic_negate(Predicate pred) : _pred(pred) {}

    template <typename... Args>
    bool operator()(Args&&... args)
    {
        return !_pred(std::forward<Args>(args)...);
    }
private:
    Predicate _pred;
};

template <class Predicate>
generic_negate<Predicate> not_(Predicate pred)
{
    return generic_negate<Predicate>(pred);
}

....

auto pos = find_if(v1.begin(), v1.end(), not_(bind(stringcasecmp, _1, target)));

: http://ideone.com/6dktf

+9

pointer_to_binary_function<string,string,int>(stringcasecmp) ptr_fun(stringcasecmp)?

0

All Articles