5

我試圖通過使用boost::bindboost::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工作正常。 當非模板函數有多個重載時,我知道如何解決類似的情況。 有人可以幫我正確寫這個嗎?或者我應該寫我自己的比較功能?

回答

8

您需要編寫static_cast<bool(*)(const std::string&, const std::string&)>(&boost::contains<..>)來解決過載問題。

是的,這是帶模板和重載的皇家痛苦。用OOP編寫並重寫的Lib很難在模板和boost :: bind中使用。

我們都等待C++ 0x lambda表達式,這應該更好地解決問題。

+0

小修正(至少在g ++ 3.4.5中) static_cast (boost :: contains <..>)。 現在它完美的工作。非常感謝您的快速提示。 – lollinus 2010-02-24 14:45:22

+0

好的。謝謝。我已經用這個更新了答案。我通常在成員函數ptrs中使用它,所以我的常規func-ptr語法顯然有點生疏。 ;) – Macke 2010-02-24 20:55:05

+0

您對模板和重載的PITA特性的坦率是非常令人放心的。在看之前,我認爲我一定是做錯了事。 – 2012-05-28 13:28:24

0

該代碼對我來說看起來很好(正確+兼容),並且它使用Visual Studio 2008進行編譯(禁用Microsoft語言擴展)。

嘗試使用更新的gcc版本。

+0

問題是,在我的生產代碼中,我無法使用其他編譯器。 – lollinus 2010-02-24 14:27:04

+1

在這種情況下,更少依賴模板魔法:編寫一個只使用boost代碼的包裝函數,並將包裝函數作爲參數傳遞給'find_if'。 – gimpf 2010-02-24 14:32:06

+0

我完全理解我可以編寫自己的函數/包裝器來進行匹配。 我只想在編寫這段代碼的時候,在我的推理中瞭解到我缺少的東西。 此外,我同意在編寫此代碼時,代碼可讀性受到影響,因爲它是可接受的解決方案。 – lollinus 2010-02-24 15:27:24