gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:02:32 25 4
gpt4 key购买 nike

我尝试了以下方法:

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) .

为什么我可以这样做?

最佳答案

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() 的结果进行初始化调用没有占位符。那很好用。 int function 的参数只是被忽略了。它可能是也可能不是您真正想要做的,但它是完全有效的代码。


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

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

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

关于c++ - 为什么我可以将可调用目标存储在与类型不匹配的 std::function 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com