Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the value category of a fold expression always prvalue?

Tags:

c++

c++17

Is a fold expression always a prvalue? Is this correct?

template<typename... Args>
auto sum(Args... args) {
    auto fold = (... +  args);
    return fold;
}

int main() {
    sum(10, 2, 2);
}

I‘m really only interested in the fold expression which is (... + args) in the above example.

like image 355
bugybunny Avatar asked Oct 04 '17 08:10

bugybunny


People also ask

What is the difference between xvalue and prvalue in C++?

In C++11, expressions that: have identity and cannot be moved from are called lvalue expressions; have identity and can be moved from are called xvalue expressions; do not have identity and can be moved from are called prvalue ("pure rvalue") expressions; do not have identity and cannot be moved from are not used.

What are glvalue and rvalue expressions?

The expressions that have identity are called "glvalue expressions" (glvalue stands for "generalized lvalue"). Both lvalues and xvalues are glvalue expressions. The expressions that can be moved from are called "rvalue expressions".

What is glvalue and prvalue in C++?

Lvalues and Rvalues (Visual C++) A glvalue is an expression whose evaluation determines the identity of an object, bit-field, or function. A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of the operand of an operator, as specified by the context in which it appears.

What is a prvalue expression?

A prvalue expression has no address that is accessible by your program. Examples of prvalue expressions include literals, function calls that return a non-reference type, and temporary objects that are created during expression evaluation but accessible only by the compiler.


1 Answers

A fold-expression has the same semantics as simply writing out the N - 1 applications of the operator (where N is the number of elements in the pack). For example, sum(10, 2, 2) will produce (10 + 2) + 2. See [temp.variadic]/9.

In general, this may or may not be an prvalue. Folding 2 or more numeric values with + will always yield a prvalue since the built-in + operator yields a prvalue, but if there is only one element in the pack args, then (... + args) means the same thing as simply mentioning that one element by its hypothetical name, so the result would be an lvalue. And of course you can fold with other (possibly overloaded) operators too, which may produce glvalues.

like image 141
Brian Bi Avatar answered Oct 19 '22 23:10

Brian Bi