Function all_checked
is meant to return true
if all calls to parse(...)
returned true
, and false
otherwise.
How can I link all the outputs together so that I effectively get
success = parse(args[0]) && parse(args[1]) && parse(args[2]) && ...;
Right now, it only returns parse(...)
for the last element.
#include <string>
template<class T>
bool parse(const T& val)
{
if constexpr (std::is_same_v<T, int> || std::is_same_v<T, std::string>)
return true;
else
return false;
}
template<class... Args>
bool all_checked(const Args& ... args)
{
bool success = (parse(args), ...); // should be true if all parse(...) are true
return success;
}
int main()
{
bool result = all_checked(1, 5.9, std::string("abc"));
}
I've tried other syntax like
bool success = true;
(success = success && parse(args), ...);
but it did not compile.
Just:
return (parse(args) && ...);
Or:
bool const success = (parse(args) && ...);
return success;
Your first version is folding over a comma, which discards all the results up until the last one:
bool success = (parse(args), ...);
evaluates as (let's assume three things):
bool success = (parse(args0), parse(args1), parse(args2));
which is the same as:
parse(args0);
parse(args1);
bool success = parse(args2);
The second would just need an extra pair of parentheses, but is just a very confusing way to write it anyway.