使用std :: bind2nd和引用 [英] Using std::bind2nd with references

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

问题描述

我有一个类似这样的简单类:

I have a simple class like this:

class A
{
public:
    void f(const int& n)
    {
    	std::cout<<"A::f()" << n <<"\n";
    }
};

,我想这样使用:

std::vector<A> vec;
A a;
vec.push_back(a);
std::for_each(vec.begin(), vec.end(), std::bind2nd(std::mem_fun_ref(&A::f), 9));

但是当我编译代码时,我在函数头文件里面得到以下错误:

But when I compile the code I get the following error somewhere inside functional header file:


错误C2529:'_Right':引用
引用是非法的

error C2529: '_Right' : reference to reference is illegal

如果我删除参数f()中的引用,它编译正常。如何解决这个问题?我不想删除引用,因为在我的实际代码复制的对象是相当昂贵的。此外,我不使用boost。

If I remove the reference in the parameter f() it compiles fine. How do I resolve this? I don't want to remove the reference as in my real code the copying of the object is quite costly. Also, I am not using boost.

推荐答案

你不能轻易做到,对不起。只要考虑其中一个没有被 std :: bind1st std :: bind2nd 参数函数等)。 Boost会帮助 - boost :: bind 透明地支持引用,还有 boost :: ref

You can't do that easily, sorry. Just consider it one of those cases not covered by std::bind1st and std::bind2nd (kinda like 3-argument functions etc). Boost would help - boost::bind supports references transparently, and there's also boost::ref.

如果你的实现支持TR1 - 最新的g ++版本和VC ++ 2008 SP1,那么你可以使用 std :: tr1 :: bind ,其大部分与 boost :: bind 相同,但标准化。

If your implementation supports TR1 - latest g++ versions and VC++2008 SP1 both do - then you can use std::tr1::bind, which is for the most part same as boost::bind, but standardized.

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

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