Using a Predicted String String Algorithm Predicate

Compiling this example

#include <boost/bind.hpp> #include <boost/algorithm/string.hpp> #include <algorithm> #include <iostream> #include <vector> using namespace std; int main(int , char** ) { vector<string> test; test.push_back("xtest2"); test.push_back("test3"); ostream_iterator<string> out_it(cout, "\n"); remove_copy_if(test.begin(), test.end(), out_it, boost::bind(boost::algorithm::starts_with, _1, "x")); } 

with an error

 no matching function for call to 'bind(<unresolved overloaded function type>, boost::arg<1>&, const char [2])' 

What is wrong with the bind call used?

+4
source share
2 answers

no matching function for call to 'bind(<unresolved overloaded function type>, boost::arg<1>&, const char [2])'

So ... resolve <unresolved overloaded function type> :

 remove_copy_if(test.begin(), test.end(), out_it, boost::bind( boost::algorithm::starts_with<std::string, std::string>, _1, "x")); 

Ouput:

 $ g++ ./test.cpp ./a.exe test3 

With a bit more work, you can make it less ugly to type. A few options below:

 #include <boost/bind.hpp> #include <boost/algorithm/string.hpp> #include <algorithm> #include <iostream> #include <vector> using namespace std; namespace my // for alternative styles { static bool starts_with(const std::string& s, const std::string& prefix) { return boost::algorithm::starts_with(s, prefix); } struct starts_with_s { starts_with_s(const std::string& prefix) : _p(prefix) {} bool operator()(const std::string& s) const { return boost::algorithm::starts_with(s, _p); } private: const std::string _p; }; } int main(int , char** ) { vector<string> test; test.push_back("xtest2"); test.push_back("test3"); ostream_iterator<string> out_it(cout, "\n"); remove_copy_if(test.begin(), test.end(), out_it, boost::bind(boost::algorithm::starts_with<std::string, std::string>, _1, "x")); remove_copy_if(test.begin(), test.end(), out_it, boost::bind(my::starts_with, _1, "x")); my::starts_with_s pred("x"); remove_copy_if(test.begin(), test.end(), out_it, pred); // using c++0x style lambdas const std::string prefix = "x"; remove_copy_if(test.begin(), test.end(), out_it, [&prefix](const std::string& s) { return boost::algorithm::starts_with(s, prefix); }); } 
+5
source

If your compiler supports some C ++ 11, you can use std :: bind. In C ++ 11, you should use std :: placeholders :: _ 1, so it will probably activate :: placeholders :: _ 1 for you.

-one
source

Source: https://habr.com/ru/post/1396175/


All Articles