使用std :: ref参数调用函数std :: bind(ed)

rel*_*xxx 2 c++ c++11

#include <functional>
#include <iostream>

struct Test
{
    void fnc(int & a) { ++a; }
};

int main ()
{
    typedef std::function<void(int)> Func;

    int i = 0;
    Test t;
    Func f = std::bind(&Test::fnc, &t, std::ref(i));
    //f(); //error C2064: term does not evaluate to a function taking 0 arguments
    f(37); //Here I am forced to pass evidently unused int
    std::cout << i;
}
Run Code Online (Sandbox Code Playgroud)

我使用它吗?

是否真的有必要传递一些随机的int?

如果是这样,为什么呢?是因为模板的魔力是有限的,我实际上必须将int传递给函数服用int OR是出于某种目的设计的吗?(例如,强迫用户不要忘记函数声明的样子如何?)

我使用vs2012

Ker*_* SB 5

不,不,你所拥有的是一个参数的函数,因为一切都已经绑定了!您需要以下两种之一:

std::function<void()> f = std::bind(&Test::fnc, &t, std::ref(i));

std::function<void(int&)> g = std::bind(&Test::fnc, &t, std::placeholders::_1);
Run Code Online (Sandbox Code Playgroud)

现在有以下两种效果t.fnc(i):

f();  // OK, bound to `i` always.

g(i); // Same effect
Run Code Online (Sandbox Code Playgroud)

请注意,如果可能,您应该声明绑定函数auto,这样更有效.第三个选项是闭包表达式[&i,&t](){t.fnc(i);}.