-2

I have the following small code example:

std::function<bool()> isSet;

bool check() {
   bool tmp;
   return tmp;
}

std::function<bool()> isSet {
    return check();
}

This gives me the following error message

could not convert 'isSet()' from 'bool' to 'std::function<bool()>'

Can anyone explain why and how I to fix it?

Swordfish
  • 12,971
  • 3
  • 21
  • 43
lg.lindstrom
  • 776
  • 1
  • 13
  • 31

2 Answers2

5

When you initialize a std::function you just give it the function you want it to use. That would look like

bool check() {
   bool tmp;
   return tmp;
}

std::function<bool()> isSet { check };

What you almost did was make a lambda, which you could do, but the syntax would be

std::function<bool()> isSet { [](){ return check(); } };

Do note that check returns an uninitialized variable which is undefined behavior: Why is returning a non-initialized value considered undefined behavior?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    Thanks,, yes,, it was a 'typo' in check to return a uninitialized. I just so sorry that there are people hanging around on stackoverflow more interested in finding errors than helping..... YOU helped alot..... Thanks. – lg.lindstrom Nov 27 '18 at 14:32
4

std::function<bool()> isSet is a regular old object, not a function. You are supposed to initialize it with a functor it can hold, not provide function block to execute.

Simply fix the initialization

std::function<bool()> isSet { check }; // Hold a pointer to check
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458