【问题标题】:std::bind: error: too few arguments to function call, single argument was not specifiedstd::bind: 错误:函数调用的参数太少,未指定单个参数
【发布时间】:2018-12-20 22:34:28
【问题描述】:

我有以下代码:

void MyClass::create_msg(MyTime timestamp) {
   // do things here ...
}

我尝试为上述函数创建一个 std::bind:

MyMsg MyClass::getResult(MyTime timestamp) {
   // do things here ...
   std::bind(create_msg(), timestamp);
   // do things ...
}

但出现以下错误:

error: too few arguments to function call, single argument 'timestamp' was not specified
    std::bind(create_msg(), timestamp);
              ~~~~~~~~~~ ^
MyClass.cpp:381:1: note: 'create_msg' declared here
void MyClass::create_msg(MyTime timestamp) {
^
1 error generated.

在这种情况下我做错了什么?谢谢!

顺便说一句,如果我这样做,同样的错误:

std::bind(&MyClass::create_msg(), this, timestamp);

【问题讨论】:

  • 是否有理由在 lambda 上使用 bind
  • @pstrjds 但它是一个成员函数,所以它必须是 std::bind(&MyClass::create_msg, this, timestamp)
  • @clcto - 你是对的 - 我的错。我打字很快,忘了考虑它是一个成员函数。
  • &MyClass::create_msg() 中去掉括号-> &MyClass::create_msg

标签: c++ stdbind


【解决方案1】:

这里有三个问题。

首先,您作为函数提供给std::bind 的参数当前是create_msg()。这意味着“调用create_msg,获取它产生的任何结果,并将其作为第一个参数传递给std::bind。”这不是您想要的 - 您的意思是“将create_msg 作为第一个参数传递给std::bind。”由于create_msg 是一个成员函数,您需要像这样获取指向它的指针:

std::bind(&MyClass::create_msg, /* ... */)

这将解决一个问题,但随后会弹出另一个问题。当您将std::bind 与成员函数指针一起使用时,您需要使用与调用该成员函数时要使用的接收器对象相对应的额外参数来证明std::bind。我相信在您的情况下,您希望当前对象成为接收者,如下所示:

std::bind(&MyClass::create_msg, this, timestamp)

这应该可以正常工作。

但是,有人可能会争辩说这里还有第三个问题 - 为什么不使用 std::bind,而不是使用 lambda 表达式?

[timestamp, this] { create_msg(timestamp); }

【讨论】:

    猜你喜欢
    • 2014-09-26
    • 1970-01-01
    • 2010-12-16
    • 2018-04-22
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多