Adriaan
Adriaan

Reputation: 715

Construct std::function from function with one known input argument and one unknown input argument

I have the function

int testFunctionA(double a,std::string b)
{
    return 0;
}

of which I want to make a std::function<int(std::string)> in which a is known and b is unknown. So something like

std::function<int(std::string)> testFunctionB=testFunctionA(2.3,std::string b);

but this syntax does not work.

What is the correct syntax?

Upvotes: 1

Views: 49

Answers (2)

WhiZTiM
WhiZTiM

Reputation: 21576

You can use std::bind:

std::function<int(std::string)> testFunc = 
         std::bind(&testFunction, 2.3, std::placeholders::_1);

Or a lambda (preferably):

std::function<int(std::string)> testFunc = 
        [](std::string str){ return testFunction( 2.3, str ); };

Upvotes: 2

clcto
clcto

Reputation: 9648

You can use a lambda:

auto func = [](std::string b){ return testFunction( 2.3, b ); };

Note: func will have some compiler generated type, but it will be implicitly convertible to a std::function< int( std::string ) >.

Upvotes: 4

Related Questions