2011-10-19 49 views
14

需要參數的方法我有一個這樣的結構:使用bind1st爲參照

struct A { 
    void i(int i) {} 
    void s(string const &s) {} 
}; 

現在,當我試試這個:

bind1st(mem_fun(&A::i), &a)(0); 
bind1st(mem_fun(&A::s), &a)(""); 

第一行編譯OK,但第二生成一個錯誤:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(299): error C2535: 'void std::binder1st<_Fn2>::operator()(const std::basic_string<_Elem,_Traits,_Ax> &) const' : member function already defined or declared 
      with 
      [ 
       _Fn2=std::mem_fun1_t<void,A,const std::string &>, 
       _Elem=char, 
       _Traits=std::char_traits<char>, 
       _Ax=std::allocator<char> 
      ] 
      c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(293) : see declaration of 'std::binder1st<_Fn2>::operator()' 
      with 
      [ 
       _Fn2=std::mem_fun1_t<void,A,const std::string &> 
      ] 
      c:\work\sources\exception\test\exception\main.cpp(33) : see reference to class template instantiation 'std::binder1st<_Fn2>' being compiled 
      with 
      [ 
       _Fn2=std::mem_fun1_t<void,A,const std::string &> 
      ] 

可能是什麼問題?我怎麼修復它?

編輯:

似乎任何引用的說法是一個問題。因此,如果我將i方法更改爲void i(int &i) {},我收到類似的錯誤。

+0

考慮到我們是在2011年,並有C++ 11你可能想看看C++ 11S'的std :: bind'或'的boost ::綁定'這使得這些事情的數量級更容易處理。 – PlasmaHH

+1

@PlasmaHH:不幸的是,我不能在這個項目中使用C++ 11。 –

+0

也不是'boost :: bind'? – PlasmaHH

回答

10

std :: bind1st和std :: bind2nd不接受帶引用參數的函子,因爲它們本身形成對這些參數的引用。您可以

  1. 您輸入的功能,而不是參考使用指針
  2. 使用的boost ::綁定
  3. 接受複製串
0

看的性能開銷在這個post人的要求解釋模板參數。 正如你已經認爲引用std :: string是問題。這不是有效的模板參數。通過指針

+1

雖然這是真的,函數的參數類型通過first_argument_type typedef從mem_fun傳輸到bind1st,並且引用是有效的typedef。因此,std :: bind1st *理論上可以接受引用,但實現方式不同(此實現由標準IIRC授權)。 – thiton

0

更改引用

#include <functional> 
#include <string> 

struct A { 
    void i(int i) {} 
    void s(const std::string *s) {} 
}; 


int main(void) 
{ 
    A a; 
    std::bind1st(std::mem_fun(&A::i), &a)(0); 
    const std::string s(""); 
    std::bind1st(std::mem_fun(&A::s), &a)(&s); 
}