2012-02-13 74 views
4

編譯這個例子使用boost字符串變換算法謂詞綁定

#include <boost/bind.hpp> 
#include <boost/algorithm/string.hpp> 
#include <algorithm> 
#include <iostream> 
#include <vector> 

using namespace std; 

int main(int , char**) 
{ 
    vector<string> test; 

    test.push_back("xtest2"); 
    test.push_back("test3"); 

    ostream_iterator<string> out_it(cout, "\n"); 

    remove_copy_if(test.begin(), test.end(), out_it,  
        boost::bind(boost::algorithm::starts_with, _1, "x")); 
} 

失敗,錯誤

no matching function for call to 
‘bind(<unresolved overloaded function type>, boost::arg<1>&, const char [2])’ 

有什麼不對所使用的bind電話嗎?

回答

5

no matching function for call to ‘bind(<unresolved overloaded function type>, boost::arg<1>&, const char [2])’

所以......解決<unresolved overloaded function type>

remove_copy_if(test.begin(), test.end(), out_it, boost::bind(
    boost::algorithm::starts_with<std::string, std::string>, _1, "x")); 

輸出繼電器:

$ g++ ./test.cpp ./a.exe 
test3 

有了多一點的工作,你可以把它不太難看鍵入。以下幾種變化:

#include <boost/bind.hpp> 
#include <boost/algorithm/string.hpp> 
#include <algorithm> 
#include <iostream> 
#include <vector> 

using namespace std; 

namespace my // for alternative styles 
{ 
    static bool starts_with(const std::string& s, const std::string& prefix) 
    { 
     return boost::algorithm::starts_with(s, prefix); 
    } 

    struct starts_with_s 
    { 
     starts_with_s(const std::string& prefix) : _p(prefix) {} 
     bool operator()(const std::string& s) const { 
      return boost::algorithm::starts_with(s, _p); 
     } 
     private: const std::string _p; 
    }; 
} 


int main(int , char**) 
{ 
    vector<string> test; 

    test.push_back("xtest2"); 
    test.push_back("test3"); 

    ostream_iterator<string> out_it(cout, "\n"); 

    remove_copy_if(test.begin(), test.end(), out_it,  
        boost::bind(boost::algorithm::starts_with<std::string, std::string>, _1, "x")); 

    remove_copy_if(test.begin(), test.end(), out_it,  
        boost::bind(my::starts_with, _1, "x")); 

    my::starts_with_s pred("x"); 
    remove_copy_if(test.begin(), test.end(), out_it, pred); 

    // using c++0x style lambdas 
    const std::string prefix = "x"; 
    remove_copy_if(test.begin(), test.end(), out_it, [&prefix](const std::string& s) 
      { return boost::algorithm::starts_with(s, prefix); }); 
} 
+0

啊,編譯器不知道'starts_with()'中有哪兩個重載我在說,所以我必須使用模板參數明確地告訴他。正確? – nabulke 2012-02-13 11:40:02

+0

確實。如果你想少做(醜)打字 – sehe 2012-02-13 11:45:23

+0

添加替代方法哇,非常感謝你這個詳盡的答案。我想我會打印出來,並用別針把它上面我的臺式機以供將來參考:-) – nabulke 2012-02-13 11:54:04

-1

如果你的編譯器支持一些C++ 11,你可以使用std ::綁定。在C++ 11中,你會使用std :: placeholders :: _ 1,所以它可能是boost :: placeholders :: _ 1。

+0

沒有'boost :: placeholders'。 '_1'工作得很好。 – nabulke 2012-02-13 11:36:05