为什么我用错误的参数可以std::bind成功?
Why can I std::bind successfully with the wrong parameters?
#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 试过代码,它们都编译结束没有错误。
绑定结果和回调的类型是否相同?一个是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.
不是你的 AddCallback() 接受了不同的类型,而是类型推导造成了混淆;
例如尝试使用
std::function<void(int)> f = std::bind(&foo, std::placeholders::_1);
或者添加回调函数我们会给你报错
Error (active) E0312 no suitable user-defined conversion from
"std::function<void (int)>" to "callback" exists
#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 试过代码,它们都编译结束没有错误。
绑定结果和回调的类型是否相同?一个是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.
不是你的 AddCallback() 接受了不同的类型,而是类型推导造成了混淆;
例如尝试使用
std::function<void(int)> f = std::bind(&foo, std::placeholders::_1);
或者添加回调函数我们会给你报错
Error (active) E0312 no suitable user-defined conversion from "std::function<void (int)>" to "callback" exists