为什么当我向作为 std::mem_fun() 的参数的成员函数添加引用参数时,它编译错误? [英] why did it compile errorly when i added a reference argument to a member function which is the argument to std::mem_fun()?

查看:28
本文介绍了为什么当我向作为 std::mem_fun() 的参数的成员函数添加引用参数时,它编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我有一个片段如下:

Firstly, I had a snippet as following:

struct D
{

  int sum;

  D():sum(0){accum();}

  void incre(int arg){sum+=arg;}

  void accum()
  {
    int arr[]={1,2,3,4,5};

    std::for_each(arr,arr+ sizeof(arr)/sizeof(int),
                  std::bind1st(std::mem_fun(&D::incre),this));

    cout << sum <<endl;
  }
};

int main()
{
  D();
}

它编译正确.但是在我将成员函数 incre 更改为

It compiled properly.But after my changing the member function incre to

void incre(int &  arg){sum+=arg;}

它产生了错误,比如

typename _Operation::result_type std::binder1st<_Operation>::operator()
    (typename _Operation::second_argument_type&) const [with _Operation = 
    std::mem_fun1_t<void, D, int&>]’ cannot be overloaded

你对正在发生的事情有什么想法吗?我将不胜感激.

Do you have any ideas about what is going on? I'll appreciate any help.

推荐答案

问题在于,在内部,mem_fun 试图将成员函数的参数类型的 const 引用设置为它的参数类型.如果使 then 函数接受引用,则它会尝试创建对引用的引用,这在 C++ 中是非法的.这是库中的一个已知缺陷,正在通过将出现在 C++0x 中的新绑定函数进行修复.

The problem is that internally, mem_fun tries to set as its argument type a const reference to the argument type of the member function. If you make then function take in a reference, then it tries to create a reference to a reference, which is illegal in C++. This is a known defect in the library and is being remedied by the new bind function that will appear in C++0x.

这篇关于为什么当我向作为 std::mem_fun() 的参数的成员函数添加引用参数时,它编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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