简体   繁体   中英

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?

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

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, eg default-constructed ones or nullptr .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM