How to bind a template function

Hi everyone, that you are raising a guru there!

I want to find a specific element in a row vector, ignoring the case:

#include <iostream> #include <string> #include <vector> #include "boost/algorithm/string.hpp" #include "boost/bind.hpp" using std::string; using std::vector; bool icmp(const string& str1, const string& str2) { return boost::iequals(str1, str2); } int main(int argc, char* argv[]) { vector<string> vec; vec.push_back("test"); // if (std::find_if(vec.begin(), vec.end(), boost::bind(&boost::iequals<string,string>, "TEST", _1)) != vec.end()) <-- does not compile if (std::find_if(vec.begin(), vec.end(), boost::bind(&icmp, "TEST", _1)) != vec.end()) std::cout << "found" << std::endl; return 0; } 

This still works, but what I would like to know is that if you can get rid of the extra function (icmp ()) and call iequals (the template function) directly (as in a commented line).

Thanks in advance!

+6
source share
3 answers

Adding template settings and a standard language setting on my computer.

 if (std::find_if(vec.begin(), vec.end(), boost::bind(&boost::iequals<string,string>, "TEST", _1, std::locale())) != vec.end()) std::cout << "found" << std::endl; 

The compiler is VS2010.

+6
source

I'm sure this is not what you are hoping for, but it is the only fix I can solve
(with g ++ C ++ 03 mode):

 typedef bool (*fptr)(const std::string&, const std::string&); if (std::find_if(vec.begin(), vec.end(), boost::bind((fptr) &boost::iequals<string,string>, "TEST", _1) ) != vec.end()) 
+2
source

Using boost lambda :)

 #include <iostream> #include <boost/lambda/bind.hpp> #include <boost/lambda/lambda.hpp> #include <algorithm> #include <vector> using namespace std; using namespace boost::lambda; int main() { vector<string> vec; vec.push_back("TEST"); vec.push_back("test"); vector<string>::iterator it; it = find_if(vec.begin(),vec.end(),_1 == "test"); cout << *it << endl; return 0; } 
+2
source

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


All Articles