Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if returned std::function is "valid" in C++11

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?

like image 416
Domi Avatar asked Nov 25 '13 12:11

Domi


2 Answers

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

like image 79
John Zwinck Avatar answered Oct 24 '22 07:10

John Zwinck


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.

like image 1
Christian Rau Avatar answered Oct 24 '22 06:10

Christian Rau