【问题标题】:How to force template function overload for boost::bind?如何为 boost::bind 强制模板函数重载?
【发布时间】:2010-02-24 14:17:05
【问题描述】:

我正在尝试使用boost::bindboost::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


    【解决方案1】:

    你需要写static_cast&lt;bool(*)(const std::string&amp;, const std::string&amp;)&gt;(&amp;boost::contains&lt;..&gt;)来解决过载问题。

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

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

    【讨论】:

    • 小修正(至少在 g++ 3.4.5 中)static_cast(boost::contains<..>)。现在它完美地工作了。非常感谢您的快速提示。
    • 好的。谢谢。我已经更新了答案。我通常将它与成员函数 ptrs 一起使用,所以我的常规 func-ptr 语法显然有点生疏。 ;)
    • 您对模板和重载的 PITA 特性的坦率非常令人放心。在看到之前,我想我一定是做错了什么。
    【解决方案2】:

    在我看来,该代码很好(正确 + 兼容),它使用 Visual Studio 2008 编译(禁用 Microsoft 语言扩展)。

    尝试使用更新版本的 gcc。

    【讨论】:

    • 问题是在我的生产代码中我不能使用另一个编译器。
    • 在这种情况下,减少对模板魔法的依赖:编写一个仅使用 boost-code 的包装函数,并将包装函数作为参数传递给find_if
    • 我完全理解我可以编写自己的仿函数/包装器来进行匹配。我只是想了解我在编写这段代码时在推理中遗漏了什么。我也同意在接受的解决方案中编写此代码时代码可读性会受到影响。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多