【发布时间】:2010-02-24 14:17:05
【问题描述】:
我正在尝试使用boost::bind 和boost::contains(来自 boost/algoritm/string 库)为std::find_if 创建谓词。
以下 sn-p 显示了我尝试实现此目的的两种方式。
#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 时,一切正常。
当有多个非模板函数重载时,我知道如何解决类似的情况。
有人可以帮我正确地写这个吗?还是我应该编写自己的比较函数?
【问题讨论】:
标签: c++ templates boost-bind boost-function overloading