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 amend the code (minimally) to make it compile?
bind2nd(§D.9) andptr_fun(§D.8.2.1) are deprecated in C++11. You could just write another lambda function infind_if:ptr_fun(<lambda>)will not work, becauseptr_funis designed for C++03 to convert a function pointer to a function object for other adaptors. A lambda is already a function object, so theptr_funis unnecessary.bind2ndexpects the function object to define the memberssecond_argument_typeandresult_type, which is not true for a lambda, so writingbind2nd(<lambda>, target)won’t work either. But in C++11 there is a generic replacement that works:However,
binddoes not return a C++03-style function object, whichnot1is expecting: it requires the type of result ofbindto define theargument_typemember which does not exist. Therefore the final expressionwill not work. The simplest workaround is just use another lambda I’ve written above.
Alternatively, you could define a generic negator:
Example: http://ideone.com/6dktf