Ankit Agarwal
Ankit Agarwal

Reputation: 124

How to use std::bind with std::function and std::map

I am trying to create a map of std::function and then trying to bind it few parameters, but it is giving an error. So, my std::function definition is

using abc = std::function<double(const double& t1, const double& t2)>;

and the map is

std::map<std::pair<std::string, std::string>, abc> conversion_;

The way I am trying to insert in this map is

conversion_.emplace(
            std::make_pair("a", "b"),
            std::bind(conversion, 3, std::placeholders::_1));

conversion_.find(std::make_pair("a", "b"))->second(4); -- Access

I have defined the function conversion, but when I am trying to access the function it is giving the below error

 error: no match for call to ‘(const std::function<double(const double&, const double&)>) (int)’

Adding full code: conversion function is defined in a separate file :

namespace x
{
    double conversion(const double& a, const double& b);
}

Header file where I am trying to define map

namespace x
{
    class main 
    {
    public:
        using abc = std::function<double(const double& t1, const double& t2)>;
        main();
    private:
        std::map<std::pair<std::string, std::string>, abc> conversion_;
    };
}

The CPP file

namespace x
{
main::main() 
{
    conversion_.emplace(
        std::make_pair("a", "b"),
        std::bind(conversion, 3, std::placeholders::_1));
    auto m = conversion_.find(std::make_pair("a", "b"))->second(4);
}
}   

Upvotes: 0

Views: 1682

Answers (1)

phyxnj
phyxnj

Reputation: 647

I guess conversion is function as double(const double& t1, const double& t2). If so, std::bind(conversion, 3, std::placeholders::_1) define a functor which requires one argument a double (the other argument of conversion is fixed as 3) and return double. You just need modify abc into std::function<double(const double& t1)>;

Upvotes: 3

Related Questions