为什么我可以将可调用目标存储在与类型不匹配的 std::function 中

Why can I store a callable target in a std::function which dosen't match the type

我试过以下方法:

typedef std::function<void(int)> callback;

struct testclass
{
    void testfunc()
    {
        printf("test\n");
    }
};

int main()
{
    testclass test;
    callback c = std::bind(&testclass::testfunc, &test);
    c(1);
}

输出为

test

std::bind returns 一个像 void(void) 这样的可调用目标,而回调应该存储在 void(int) 中。

为什么我可以这样做?

std::bind 返回一个函数对象,它忽略任何没有关联占位符的参数。这是一场松散的比赛。

例如:

auto f = []{}; // no arguments, do nothing
f(1); // obviously ill-formed

auto g = std::bind(f);
g(); // okay, calls f()
g(1); // okay, calls f()
g(1, 2); // okay, calls f()

在您的示例中,您有一个 function<void(int)>,您正在使用不带占位符的 std::bind() 调用的结果进行初始化。那很好用。 functionint 参数被忽略了。它可能是也可能不是您真正想要做的,但它是完全有效的代码。


使用 lambda,您可以通过以下方式获得相同的效果:

callback c = [&test](int){ test.testfunc(); };

这里我们必须显式地写参数,而 bind 它被隐式地忽略了。