gpt4 book ai didi

c++ - c++中函数对象之间不匹配的函数签名

转载 作者:行者123 更新时间:2023-11-30 03:38:58 28 4
gpt4 key购买 nike

我得到了如下代码片段,并构建了它:

#include <functional>

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

void falseRead() {}

int main()
{
ReadCallback callback = std::bind(falseRead);
}

ReadCallback 的签名是void(int),而falseRead 的签名是void()。分配如何发生?

如果我使用callback 对象来调用函数,我应该使用哪个语句,callback()callback(0)

最佳答案

绑定(bind)表达式可以用任意数量的参数调用;与占位符不对应的参数将被丢弃。

auto f = std::bind(falseRead);

f(a, b, c); // equivalent to falseRead();

因此,您的绑定(bind)表达式可用于构造 std::function<void(int)>对象:

std::function<void(int)> g = f;

g(a); // = f(a) = falseRead()

这是被禁止的相反方向:如果你的绑定(bind)函数接受参数,你必须为参数提供值(绑定(bind)值或占位符):

void realRead(int fd, char* buf);

auto h = std::bind(realRead, _1, buf); // h(fd) = realRead(fd, buf)
// auto h = std::bind(realRead); // error

关于c++ - c++中函数对象之间不匹配的函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39135585/

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