Home > Blockchain >  std::function, it must have template argument?
std::function, it must have template argument?

Time:03-04

void hello(float i)
{
    std::cout << "hello" << i << "\n";
}

int hollo(int a)
{
    std::cout << "good" << a;
    return 0;
}

int main(int, char**)
{
    std::function hallo = hello;
    hallo(3.0f);
    
    hallo = hollo;
    hallo(3);
    
    while (true) {}
}

My code above works.

First, can I really use std::function without inserting a template argument, unlike internet examples?

Second, does this way of not using the template argument have any bad effects (decreasing performance, making the code hard to be managed and checked for type, or anything)?

Or, did it have any good effect (yea, I can make any function get into std::function only using =, it makes me happy)?

CodePudding user response:

Can I use std::function without inserting template argument

Yes and no. std::function is a class template, and it must have template arguments, but (since C 17) those template arguments may be deduced from the function arguments of the constructor, in which case you don't have to specify the template arguments explicitly.

// deduced as std::function<void(float)>
std::function hallo = hello;

// no deduction; ill-formed
std::function broken;

CodePudding user response:

The other answer says why this is allowed, but I want to mention that not specifying template arguments may cause readability issues sometimes. For example in the code you have shown, what do you expect the second call hallo(3); to do?

I assume you think that simply hollo is called with argument 3, but that is not the case. The type of hallo was deduced as std::function<void(float)> and that doesn't change in the assignment hallo = hollo;. So, actually, the argument 3 is first cast to float and then passed to hollo which implies that it is cast back to int again. These casts may change the value that ends up as the hollo argument. (Although very likely not for the value 3 specifically.)

Similarly you may expect hallo(3) to return an int, but it doesn't since the deduced function type for std::function has return type void.

  •  Tags:  
  • c
  • Related