c++ - 为什么我可以使用错误的参数成功地 std::bind?

标签 c++ c++11 stdbind

#include <iostream>
#include <functional>

using callback = std::function<void(int, void*)>;

void AddCallback(callback cb) {}

void foo(int i) {}

int main() {
  auto f = std::bind(&foo, std::placeholders::_1);
  AddCallback(f);
}
我用 g++ 9.3.0 和 clang++ 10.0.0 尝试了代码,它们都编译结束没有错误。
绑定(bind)结果的类型和回调的类型是否相同?一种是std::function<void(int, void*)> , 另一个等于 std::function<void(int)> ?为什么我可以调用AddCallback()有不同的类型?

最佳答案

看来您可以将更多参数传递给 bind 的结果不必要的,它们将被默默地忽略。

If some of the arguments that are supplied in the call to [the result of bind] are not matched by any placeholders ..., the unused arguments are evaluated and discarded.

cppreference

关于c++ - 为什么我可以使用错误的参数成功地 std::bind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62711866/

相关文章:

c++ - 为什么 std::bind 在绑定(bind)到成员函数时无法编译?

C++ 字符串有垃圾字符

c++ - Microsoft Visual C++ 的 OpenMP 更新,仍然停留在版本 2 上

c++ - 性能调优

c++ - 在 c++ () 或 {} 中委托(delegate)构造函数

c++11 - VS2015 的链式 std::bind 编译错误

c++ - 无需单例即可将 QML 与 C++ 连接

c++ - 使用 VS2010 SP1 的函数模板中的编译器错误

c++ - 为什么 std::reference_wrapper 不是默认可构造的?

c++ - 有没有办法创建由 `std::function<>` 包装的函数的哈希值?