Using std::tr1::bind with std::vector::push_back

后端 未结 4 817
孤独总比滥情好
孤独总比滥情好 2021-01-21 15:39

Why my VS2010 can\'t compile this code:

#include 
#include 
int main()
{
    std::vector vec;
    std::bind(&std::         


        
4条回答
  •  走了就别回头了
    2021-01-21 16:11

    Try this:

    struct push_back {
        void
        operator()(std::vector& vector, int i) const
        {
            vector.push_back(i);
        }
    };
    
    // somewhere else:
    std::vector vec;
    std::tr1::bind(push_back(), std::tr1::ref(vec), 1)();
    

    With C++03 note that push_back cannot be a local type; with C++11 it can but it would be more idiomatic (and completely equivalent) to use a lambda.

    In all likeliness your implementation provides overloads for std::vector::push_back and thus its address would have to be disambiguated. If this is what happened, your compiler should have provided you with an appropriate error message. In all cases, you should explain what you mean by "it's not possible".


    The point is not to use such helper functions. – magenta

    Then why didn't you put it in the question? I can't read your mind.

    You can also try this:

    std::vector vec;
    void (std::vector::*push_back)(int const&) = &std::vector::push_back;
    std::tr1::bind(push_back(), std::tr1::ref(vec), 1)();
    

    Which I believe is not guaranteed to success.

提交回复
热议问题