使用std :: tr1 :: bind和std :: vector :: push_back [英] Using std::tr1::bind with std::vector::push_back

查看:212
本文介绍了使用std :: tr1 :: bind和std :: vector :: push_back的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的VS2010无法编译此代码:

  #include< functional& 
#include< vector>
int main()
{
std :: vector< int> vec;
std :: bind(& std :: vector< int> :: push_back,std :: ref(vec),1)
return 0;
}


解决方案

>

  struct push_back {
void
operator()(std :: vector< int>& vector,int i )const
{
vector.push_back(i);
}
};

//其他地方:
std :: vector< int> vec;
std :: tr1 :: bind(push_back(),std :: tr1 :: ref(vec),1)();使用C ++ 03注意, push_back

不能是本地类型;使用C ++ 11它可以,但它会更加惯用(和完全等效)使用lambda。



在所有可能性你的实现提供重载 std :: vector< T> :: push_back ,因此其地址必须被消除歧义。如果这是发生了什么,你的编译器应该提供了一个适当的错误消息。在全部的情况下,您应该用不可能解释您的意思。







要点是不要使用这样的帮助器
函数。 - magenta


那么你为什么不把它放在问题中呢?



您也可以尝试:

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

我相信这不能保证成功。


Why my VS2010 can't compile this code:

#include <functional>
#include <vector>
int main()
{
    std::vector<int> vec;
    std::bind(&std::vector<int>::push_back, std::ref(vec), 1)();
    return 0;
}

解决方案

Try this:

struct push_back {
    void
    operator()(std::vector<int>& vector, int i) const
    {
        vector.push_back(i);
    }
};

// somewhere else:
std::vector<int> 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<T>::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<int> vec;
void (std::vector<int>::*push_back)(int const&) = &std::vector<int>::push_back;
std::tr1::bind(push_back(), std::tr1::ref(vec), 1)();

Which I believe is not guaranteed to success.

这篇关于使用std :: tr1 :: bind和std :: vector :: push_back的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆