1

I don't know what's happening in this code.

SimpleFunction(1,2,3) is equal to

1&&(2&&3) //1

1||(2||3) //1

SimpleFunction(1) is equal to

1&&Something //1

1||Something //1

SimpleFunction() is equal to

voidvalue (&&) //1

voidvalue (||) //0

What is 'Something?'

and what is happening in SimpleFunction(void)??

Is it special something about Logical operator in unary fold??

#include<iostream>
using namespace std;


template <typename ...Ts>
void SimpleFunction(Ts ... ts)
{
    cout<<(ts && ...)<<endl;
    cout<<(ts || ...)<<endl;
}

int main()
{
SimpleFunction(); // 1, 0
cout<<endl;

SimpleFunction(1); // 1, 1
cout<<endl;

SimpleFunction(1,2,3); // 1, 1
cout<<endl;

return 0;
}
Davis Herring
  • 36,443
  • 4
  • 48
  • 76
Scha
  • 13
  • 2
  • Perhaps [this fold reference](https://en.cppreference.com/w/cpp/language/fold) could be helpful? – Some programmer dude Jul 27 '19 at 06:35
  • When a unary fold is used with a pack expansion of length zero, only the following operators are allowed: 1) Logical AND (&&). The value for the empty pack is true 2) Logical OR (||). The value for the empty pack is false 3) The comma operator (,). The value for the empty pack is void() – Scha Jul 27 '19 at 06:40
  • As for single-argument variant, `pack op ...` is always equal to `pack` (for your example `ts && ...` and `ts || ...` will always be just plain `ts`). – Some programmer dude Jul 27 '19 at 06:42
  • OK, I understand result of SimmpleFunc() is the set rule, and SimpleFunc(1) is always equal to (1).... Thanks to your help. – Scha Jul 27 '19 at 06:48
  • 1
    @Scha: Your comments should be a (self-)answer (unless someone can identify a duplicate). – Davis Herring Jul 27 '19 at 21:51
  • @DavisHerring We may need a FAQ for fold expressions. – L. F. Jul 28 '19 at 02:30

1 Answers1

0

When the pack contains zero elements, unary && and || folds are defined to return true and false, respectively. In fact, they are two of the only three operators that allow folding with zero elements, with the last one being the comma operator ,, which returns a prvalue of type void. This is why code like nums + ... should usually be rewritten as nums + ... + 0.

When the pack contains one element, a fold expression always expands to the only element.

Why? This is what the standard says. Because it is defined the only way that makes sense. There isn't much more to say other than that.

L. F.
  • 19,445
  • 8
  • 48
  • 82