5

I want to implement a dynamic task queue like so:

typedef std::function<void(void)> Job;
typedef std::function<Job(void)> JobGenerator;

// ..

JobGenerator gen = ...;
auto job = gen(); 
while (IsValidFunction(job))
{
    job();
}

How can i implement IsValidFunction? Is there a sort of default value for std::function to check against?

Domi
  • 22,151
  • 15
  • 92
  • 122

2 Answers2

10

You can simply check job as a bool:

while (auto job = gen())
{
    job();
}

That's a sort of shorthand which assigns job from gen() each time through the loop, stopping when job evaluates as false, relying on std::function<>::operator bool: http://en.cppreference.com/w/cpp/utility/functional/function/operator_bool

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Good stuff. I already knew about [conversion operators](http://stackoverflow.com/questions/1383606/conversion-operators-in-c), but I forgot about them entirely! I think, [this link](http://stackoverflow.com/questions/4600295/what-is-the-meaning-of-operator-bool-const-in-c) explains the concept better. – Domi Nov 25 '13 at 14:15
  • Careful @Domi, there are bugs on the `bool` conversion of `std::function` in the wild: http://stackoverflow.com/questions/19578237/strange-behavior-with-stdfunction – Yakk - Adam Nevraumont Nov 25 '13 at 14:50
1

You could just check if the function has a valid target, by using its conversion to bool. Non-valid functions would then be empty ones which don't have a target, e.g. default-constructed ones or nullptr.

Christian Rau
  • 45,360
  • 10
  • 108
  • 185