1

When I read std::function, I find the following syntax confusing. What does a struct followed directly by empty parentheses do here? It works equivalent to declare a struct object instead and call its operator.

#include <iostream>

using namespace std;

int main() {

    struct F {
        bool operator()(int a) {
            return a>0;
        }
    };

    function<bool(int)> f = F(); //What does the syntax F() mean here?
    struct F ff;
    cout <<  f(1) <<endl; 
    cout << ff(1) <<endl;
    return 0;
}
lkahtz
  • 4,706
  • 8
  • 46
  • 72

2 Answers2

3

What does the syntax F() mean here?

It means construct an object of type F using the default constructor.

A std::function can be constructed using any callable object that meets its calling criteria. In your particular use case, an instance of F meets those criteria for std::function<bool(int)>. Hence,

function<bool(int)> f = F();

is a valid statement to construct f.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks. This helps. The last still puzzling to me is what is the F() doing here? I presume it returns something like `new F()`? – lkahtz Jun 27 '16 at 20:04
  • 2
    @lkahtz It simply returns an object instance of type `F` where as `new F()` would return **a pointer** to an object instance of type `F`. – James Adkison Jun 27 '16 at 20:05
  • 1
    @lkahtz, to add to the comment James Adkison, `new F()` will allocate memory for an object from the heap, construct an object of type `F` using that memory, and then return a pointer to that object. – R Sahu Jun 27 '16 at 20:09
  • Thanks James, Tobi and R Sahu – lkahtz Jun 27 '16 at 20:31
2

Dont get confused by the fact that calling the default constuctor also uses (). This

function<bool(int)> f = F();

calls the constructor and assigns the object to the function f, while this

f(1)

calls the operator().

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • Thanks. So `F()` is actually calling the constructor here. It still confuses me that a struct constructor is called without `new`. And why is a template class instance `f` declared and assigned here, by the returned value of a struct constructor? – lkahtz Jun 27 '16 at 19:57
  • 1
    @lkahtz See the first answer provided by @RSahu for the details of `f`. – James Adkison Jun 27 '16 at 20:03
  • 2
    @lkahtz dont use `new` to construct objects if you dont need to. Objects are simply constructed by calling the constructor (hence its name ;). – 463035818_is_not_an_ai Jun 27 '16 at 20:07