Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c++ - Using bind1st for a method that takes argument by reference

I have a struct like this:

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

Now when I try this:

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

The first line compiles OK, but the second generates an error:

c:program files (x86)microsoft visual studio 10.0vcincludexfunctional(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.0vcincludexfunctional(293) : see declaration of 'std::binder1st<_Fn2>::operator ()'
          with
          [
              _Fn2=std::mem_fun1_t<void,A,const std::string &>
          ]
          c:worksourcesexceptionestexceptionmain.cpp(33) : see reference to class template instantiation 'std::binder1st<_Fn2>' being compiled
          with
          [
              _Fn2=std::mem_fun1_t<void,A,const std::string &>
          ]

What could be the problem? How could I fix it?

Edit:

It seems that any reference argument is a problem. So if I change the i method to void i(int &i) {} I get a similar error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

std::bind1st and std::bind2nd don't accept functors which take reference arguments, because they themselves form references to these arguments. You can

  1. use pointers for your function inputs instead of references
  2. use boost::bind
  3. accept the performance cost of copying the string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...