std :: function和std :: bind返回值

问题描述 投票:1回答:1

我试图了解std :: bind和std :: function是如何工作的。我无法编译以下代码:

#include <iostream>
#include <string>
#include <functional>

void function(int a, float b, std::string const &s)
{
    std::cout << "printing function" << std::endl;
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << s << std::endl;
}

int main(int argc, char *argv[])
{
    std::bind(&function, 10, 11.1, "hello")();
    std::function<void(int, float, std::string const&)> fun = std::bind(&function, 10, std::placeholders::_1, std::placeholders::_2);

    fun(0.2, "world");

    return 0;
}

编译器抱怨说:

main.cpp: In function 'int main(int, char**)':
main.cpp:16:69: error: conversion from 'std::_Bind_helper<false, void (*)(int, float, const std::__cxx11::basic_string<char>&), int, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type {aka std::_Bind<void (*(int, std::_Placeholder<1>, std::_Placeholder<2>))(int, float, const std::__cxx11::basic_string<char>&)>}' to non-scalar type 'std::function<void(int, float, const std::__cxx11::basic_string<char>&)>' requested
  std::function<void(int, float, std::string const&)> fun = std::bind(&function, 10, std::placeholders::_1, std::placeholders::_2);
                                                            ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

拜托,有人能解释一下吗?以及如何解决此错误?

c++ std-function stdbind
1个回答
4
投票

你几乎就在那里,只需将fun的类型更改为

std::function<void(float, std::string const&)> fun = std::bind(...);
//                ^^ no more int here

fun(0.2, "world");
//  ^^^^^^^^^^^^ those types must match the above signature

请注意,在将int类型的第一个函数参数固定为值10时,请更改函数签名。因此,它不能是std::function实例化的类型。

进一步注意,Scott Meyers在有效现代C ++的第34项中建议用lambda取代std::bind用法,例如:

auto fun = [](float b, std::string const& s){ function(10, b, s); };

// Identical invocation:
fun(0.2, "world");
© www.soinside.com 2019 - 2024. All rights reserved.