std :: function и std :: bind возвращаемое значение - PullRequest
1 голос
/ 12 марта 2019

Я пытаюсь понять, как работают 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);
                                                            ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

пожалуйста, кто-нибудь может объяснить? и как мне исправить эту ошибку?

1 Ответ

4 голосов
/ 12 марта 2019

Вы почти у цели, просто измените тип 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 экземпляра.

Далее отметим, что Скотт Мейерс предлагает в пункте 34 «Эффективного современного C ++» заменить использование std::bind на лямбду, например

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

// Identical invocation:
fun(0.2, "world");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...