我試圖通過使用boost::bind
和boost::contains
(來自boost/algoritm/string library)來創建std::find_if
的謂詞。 以下片段顯示了兩種方法,我試圖完成此操作。如何強制boost :: bind模板函數重載?
#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
哪一個只有一個過載everyting工作正常。 當非模板函數有多個重載時,我知道如何解決類似的情況。 有人可以幫我正確寫這個嗎?或者我應該寫我自己的比較功能?
小修正(至少在g ++ 3.4.5中) static_cast(boost :: contains <..>)。 現在它完美的工作。非常感謝您的快速提示。 –
lollinus
2010-02-24 14:45:22
好的。謝謝。我已經用這個更新了答案。我通常在成員函數ptrs中使用它,所以我的常規func-ptr語法顯然有點生疏。 ;) – Macke 2010-02-24 20:55:05
您對模板和重載的PITA特性的坦率是非常令人放心的。在看之前,我認爲我一定是做錯了事。 – 2012-05-28 13:28:24