为什么std :: function可以隐式转换为具有更多参数的std :: function? [英] Why does std::function can implicit convert to a std::function which has more parameter?

查看:87
本文介绍了为什么std :: function可以隐式转换为具有更多参数的std :: function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

void print_str(std::shared_ptr<std::string> str) {
    std::cout << str->c_str() << std::endl;
}

int main() {
    auto str = std::make_shared<std::string>("Hello");
    std::function<void()> f = std::bind(print_str, str);

    f(); // correctly print: Hello

    return 0;
}

我认为 std :: bind(print_str,str)的类型是 std :: function< void(std :: shared_ptr< std :: string>)> 代码>,但是上面的代码正在正确运行. std :: bind 中有什么花招吗?

I think the type of std::bind(print_str, str) is std::function<void(std::shared_ptr<std::string>)>, but the code above is correctly running. Is there any trick in std::bind?

env:centos,gcc82

env: centos, gcc82

推荐答案

std :: bind所做的操作是正确的.它使用您提供的值(str)来调用print_str.因此,您不再需要指定它,它将始终被绑定值替换.

What std::bind does is correct. It uses the value you provided (str) for the call to print_str. So you don't need to specify it anymore and will always be replaced by the bound value.

#include <iostream>
#include <functional>

int sum(int value1, int value2) {
    return value1 + value2;
}

int main() {

    std::function<int(int, int)> f1 = std::bind(sum, std::placeholders::_1, std::placeholders::_1);
    std::function<int(int)> f2 = std::bind(sum, 10, std::placeholders::_1);
    std::function<int()> f3 = std::bind(sum, 100, 200);
    std::function<int(int)> f4 = std::bind(sum, std::placeholders::_1, 200);

    int a = 1;
    int b = 2;

    std::cout << "the sum of " << a << " and " << b << " is: " << f1(a, b) << std::endl;
    std::cout << "the sum of " << 10 << " and " << b << " is: " << f2(b) << std::endl;
    std::cout << "the sum of " << 100 << " and " << 200 << " is: " << f3() << std::endl;
    std::cout << "the sum of " << 200 << " and " << b << " is: " << f4(b) << std::endl;

    return 0;
}

输出:

the sum of 1 and 2 is: 2
the sum of 10 and 2 is: 12
the sum of 100 and 200 is: 300
the sum of 200 and 2 is: 202

f1 除了占位符外不绑定任何值,并返回类似函数的 int(int,int)

f1 binds no values but placeholders and returns an int(int, int) like function

f2 绑定一个值和一个占位符,并返回类似函数的 int(int)

f2 binds one value and one placeholder and returns an int(int) like function

f3 绑定两个值且没有占位符,并返回类似函数的 int()

f3 binds two values and no placeholder and returns an int() like function

f4 f2 相似,不同之处在于,占位符现在是第一个参数,而不是第二个参数.

f4 is like f2 except that the place holder is now the first parameter instead of the second one.

您的代码属于 f3 案.

这篇关于为什么std :: function可以隐式转换为具有更多参数的std :: function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆