c++ - 为什么转换为 std::function 没有编译错误

标签 c++ function bind

为什么带有 p1 和 p2 的行编译正常?

它们有不同的类型

#include <functional> 
#include <iostream>


void cb(int X)
{
    std::cout << X << "\n";
}

int main(void) {

 std::function<void(void)> p1 = std::bind(cb, 9);
 std::function<void(int)>  p2 = std::bind(cb, 5);    

 //p1 = p2;
}

如果我取消注释行 p1=p2 - 编译错误

最佳答案

std::bind 调用创建的函数对象会忽略所有额外的参数。示例:

void f(int);

int main() {
    auto a = std::bind(f, 42);
    a();
    a(1);
    a(1, 2, 3);
}

您可以将此类对象分配给采用相同或更多数量参数的 std::function。同样,额外的参数将被默默地忽略。

C++11 lambda 更高效,额外的参数会导致编译器错误(例如尝试 auto a = []() { f(42); };)。

关于c++ - 为什么转换为 std::function 没有编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53707656/

相关文章:

c++ - opencv 是如何工作的?

python - 类型错误:不支持的操作数类型/: 'list' 和 'int'

javascript - 访问 jQuery 中新生成的内容

javascript - 如何从具有 id 的元素发送文本以在单击时起作用?

php - 页面加载错误codeigniter

c++ - boost::bind 与空函数指针

c++ - 返回 std::function 的类 std::bind 函数

c++ - 成员初始化列表 : initialize two members from a function returning a tuple

c++ - 这是 g++ c++14 支持中的错误吗?

c++ - 构造函数中的非零默认值