代码之家  ›  专栏  ›  技术社区  ›  lollinus

如何为boost::bind强制模板函数重载?

  •  5
  • lollinus  · 技术社区  · 16 年前

    我正在尝试为创建谓词 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 每次只有一个超负荷工作正常。 我知道如何解决非模板函数存在多个重载的类似情况。 有人能帮我把这个写得正确吗?还是应该编写自己的比较函数?

    2 回复  |  直到 16 年前
        1
  •  8
  •   Macke    16 年前

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

    是的,这是一个皇家痛苦与模板和超载。考虑到OOP和重载的libs很难与模板和boost::bind一起使用。

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

        2
  •  0
  •   JoeG    16 年前

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

    尝试使用更新版本的gcc。