c++ - std::bind 不适用于引用?

标签 c++ reference compilation bind

我有以下程序并且可以运行:

#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;
void f(int i,int j){
    ++i;
    ++j;
}
int main(){
    int i=0;
    int j=0;
    bind(&f,_1,i)(3);
    bind(&f,j,_1)(4);
    return 0;
}

但是,如果我将 f 更改为接收引用,并将 ref() 添加到绑定(bind)中:

#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;
void f(int &i,int &j){
    ++i;
    ++j;
}
int main(){
    int i=0;
    int j=0;
    bind(&f,_1,ref(i))(3);
    bind(&f,ref(j),_1)(4);
    return 0;
}

编译失败:

clang --std=c++11 给出以下错误:

no matching function for call to object of type '__bind<void (*)(int &,
  int &), std::__1::placeholders::__ph<1> &, int &>'
bind(&f,_1,i)();

如何解决?

最佳答案

bind(&f, _1, ref(i))(3);
bind(&f, ref(j), _1)(4);

一般来说,这和调用是一样的:

f(3, i);
f(j, 4);

其中函数 f 定义为:

void f(int &i, int &j) {
    ++i;
    ++j;
}

但是您不能将非常量左值引用(如int &i)绑定(bind)到右值(如3 ),这就是编译器提示的原因。

关于c++ - std::bind 不适用于引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45345482/

相关文章:

c++ - 在源文件中放置模板成员函数的特化定义(没有默认主体)是否安全?

c++ - 如何访问内存映射 USB 主机 Controller 寄存器?

Bash 间接变量引用

perl - 从函数返回散列的最佳 Perl 实践是什么?

c++ - C/C++ 优化器能否决定延迟评估仅用于短路评估的值?

c - 哦不,不是另一个 undefined reference 问题!

c++ - 如何检查可能使用 SFINAE 的类型中是否存在字段?

c++ - 如何修复编译错误 : non-template 'iterator1' used as template

c++ - 指向引用的指针是否指向引用的地址或值?

compilation - rdmd 命令无法识别