【问题标题】:Why can I store a callable target in a std::function which dosen't match the type为什么我可以将可调用目标存储在与类型不匹配的 std::function 中
【发布时间】:2019-07-10 11:04:10
【问题描述】:

我尝试了以下方法:

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 返回一个可调用的目标,如void(void),而回调应存储为void(int)

为什么我可以这样做?

【问题讨论】:

  • 可能是因为bind返回A function object of unspecified type...

标签: c++ c++11 stdbind


【解决方案1】:

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&lt;void(int)&gt;,您正在使用不带占位符的 std::bind() 调用的结果进行初始化。这很好用。 functionint 参数被忽略。它可能是也可能不是您真正想要做的,但它是完全有效的代码。


使用 lambda,您可以通过编写获得相同的效果:

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

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

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2019-07-04
    • 2022-01-26
    相关资源
    最近更新 更多