我正在尝试std::find_if
通过boost::bind
与boost::contains
(来自 boost/algoritm/string 库)一起使用来创建谓词。以下代码段显示了我尝试实现此目的的两种方式。
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <string>
int main(int argc, char** argv) {
std::string s1("hello mom");
std::string s2("bye mom");
boost::function<bool (std::string, std::string)> f = &boost::contains<std::string, std::string>;
std::cout << s1 << " contains " << "hello, " << std::boolalpha << f(s1, "hello") << std::endl;
std::cout << s2 << " contains " << "hello, " << std::boolalpha << f(s2, "hello") << std::endl;
boost::function<bool (std::string)> contain_hello = boost::bind(boost::contains<std::string, std::string>, _1, std::string("hello"));
std::cout << s1 << " contains " << "hello, " << std::boolalpha << contain_hello(s1) << std::endl;
std::cout << s2 << " contains " << "hello, " << std::boolalpha << contain_hello(s2) << std::endl;
return EXIT_SUCCESS;
}
使用 g++ 3.4.5 编译此代码时,我得到以下输出。
error: conversion from `<unresolved overloaded function type>' to non-scalar type `boost::function<bool ()(std::string, std::string), std::allocator<void> >' requested
error: no matching function for call to `bind(<unresolved overloaded function type>, boost::arg<1>&, std::string)'
当我切换到boost::icontains
只有一个过载的情况下,一切正常。当有多个非模板函数重载时,我知道如何解决类似的情况。有人可以帮我正确地写这个吗?还是我应该编写自己的比较函数?