1

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.

Phil-ZXX
  • 2,359
  • 2
  • 28
  • 40
  • 1
    Fix for your last syntax `((success = (success && parse(args))), ...)`. Even if `return (parse(args) && ...);` is simpler. – Jarod42 Aug 27 '19 at 16:39

2 Answers2

4

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
4

Your fold expression should be in the form of (<expression> <operation to fold> ...). Using that your all_checked becomes

template<class... Args>
bool all_checked(const Args& ... args)
{
    return (parse(args) && ...);  // should be true if all parse(...) are true
}

You can also change

template<class T>
bool parse(const T& val)

to

template<class T>
bool parse(const T&)

so you don't get a bunch of warning about an unused variable since you never actually use val.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402