5

我正在尝试std::find_if通过boost::bindboost::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只有一个过载的情况下,一切正常。当有多个非模板函数重载时,我知道如何解决类似的情况。有人可以帮我正确地写这个吗?还是我应该编写自己的比较函数?

4

2 回答 2

8

您需要编写static_cast<bool(*)(const std::string&, const std::string&)>(&boost::contains<..>)以解决过载问题。

是的,这是模板和重载带来的痛苦。使用 OOP 和重载编写的库很难与模板和 boost::bind 一起使用。

我们都在等待 C++0x lambda 表达式,它应该可以更好地解决问题。

于 2010-02-24T14:32:54.967 回答
0

该代码对我来说看起来不错(正确 + 兼容),并且它使用 Visual Studio 2008 进行编译(禁用了 Microsoft 语言扩展)。

尝试使用更新版本的 gcc。

于 2010-02-24T14:26:07.477 回答