Home > OS >  std::function argument binding
std::function argument binding

Time:11-23

Can someone explain me why some of these implementation works while other doesn't and what's happening under the hood? Is there some performance issue for example with f1?

What should I google for finding these mapping rules?

#include<string> 
#include <algorithm>
#include <vector> 
#include <iostream>
#include <functional> 

bool f1(const std::string& str1)  //works
{
    std::cout<<"f1"<<str1<<std::endl;
    return true;
}

bool f2(std::string& str1) //not working
{
    std::cout<<"f2"<<str1<<std::endl;
    return true;
}

bool f3(std::string str1) //works
{
    std::cout<<"f3"<<str1<<std::endl;
    return true;
}

bool f4(std::string* str1)
{
    std::cout<<"f4"<<str1<<std::endl;
    return true;
}

int main(){
    std::function<bool(std::string)> fp=&f1;
    std::string x="Hello world";
    fp(x);
    return 0;
}

CodePudding user response:

As explained on cppreference, you can assign a function f to a std::function<R(Args...)> if f is callable for argument types Args... and return type R.

In your example, f1 and f3 work because you can call either of them with a std::string rvalue. You can't call f2 or f4 with a std::string rvalue.

CodePudding user response:

Your function definition must match bool(std::string)

Only f1 and f3 match it. However, f2 and f4 don't match std::string.

Non const reference or pointer to std::string cannot convert to std::string. But const reference can.

  • Related