Using bind1st for a method that takes argument by reference

后端 未结 4 1072
悲哀的现实
悲哀的现实 2020-12-01 20:59

I have a struct like this:

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

Now when I try this:

bind         


        
相关标签:
4条回答
  • 2020-12-01 21:30

    Change references by pointers

    #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);
    }
    
    0 讨论(0)
  • 2020-12-01 21:32

    Look at this post were the requirements of template parameters are explained. As you already assumed the reference to the std::string is the problem. It's not a valid template parameter.

    0 讨论(0)
  • 2020-12-01 21:46

    The issue is a defect in the library specification.

    Take a look at this bug report against gcc and the resulting discussion: Bug 37811 - bind1st fails on mem_fun with reference argument

    C++03 lacked the facilities to build a perfect bind library. This issue is fixed in C++11 with perfect forwarding and std::bind.

    0 讨论(0)
  • 2020-12-01 21:47

    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
    0 讨论(0)
提交回复
热议问题