lol*_*nus 5 c++ templates overloading boost-bind boost-function
我正在尝试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;
}
Run Code Online (Sandbox Code Playgroud)
用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)'
Run Code Online (Sandbox Code Playgroud)
当我切换到boost::icontains只有一个过载时,每个工作正常.我知道当非模板函数有多个重载时如何解决类似情况.有人可以帮我写这个吗?或者我应该编写自己的比较功能?
您需要编写static_cast<bool(*)(const std::string&, const std::string&)>(&boost::contains<..>)以解决重载问题.
是的,这是模板和重载的皇家痛苦.用OOP编写并且重载的Libs很难用于模板和boost :: bind.
我们都在等待C++ 0x lambda表达式,它应该更好地解决问题.