Search code examples
castingoperator-keywordfoldc++17operator-precedence

C++17: What does "operator with precedence below cast" mean in "fold" concept?


The website of http://en.cppreference.com/w/cpp/language/fold gives an example of how to use fold concept, and it says:

Note
If the expression used as init or as pack has an operator with precedence    
below cast at the top level, it can be parenthesed:

template<typename ...Args>
int sum(Args&&... args) {
//    return (args + ... + 1 * 2); // Error: operator with precedence below cast
    return (args + ... + (1 * 2)); // OK
}

As a non-native English speaker, I don't quit get the sentence:

has an operator with precedence below cast at the top level

What does it actually mean, and it the example, what does it indicate? Could you help to explain this?

Thanks a lot.


Solution

  • The casting operator ((Typename)expr) has a very high precedence in C++'s operator precedence rules. Very few operators have higher precedence than that. Operators of cast level or greater precedence are very special operations, usually applying to a single expression.

    In the expression args + ... + 1 * 2, the ... applies to everything both on the left and the right. But what does "on the right" really mean? Does it mean just the + 1 part, or does it mean + 1 * 2?

    In the case of operators with high precedence, it's clear what the intent is. For example, args + ... + func(), it's clear that the () function call operator applies to func and not to args + ... + func. It's so unlikely that you would want the latter that you are forced to use parenthesis explicitly if you did ((args + ... + func)()).

    However for precedence levels below 3 in the chart, things become much more cloudy for people to understand. So instead of using the normal precedence rules, C++ forces the user to be explicit about it. You can have args + ... + (1 * 2) or (args + ... + 1) * 2. But you have to be clear which one you want.