Why use std::forward in concepts?

前端 未结 2 1042
滥情空心
滥情空心 2021-02-07 02:07

I was reading the cppreference page on Constraints and noticed this example:

// example constraint from the standard library (ranges TS)
template 

        
2条回答
  •  礼貌的吻别
    2021-02-07 02:28

    Don't we want to call swap with lvalues […]

    That’s a very good question. A question of API design specifically: what meaning or meanings should the designer of a concept library give to the parameters of its concepts?

    A quick recap on Swappable requirements. That is, the actual requirements that already appear in today’s Standard and have been here since before concepts-lite:

    • An object t is swappable with an object u if and only if:
      • […] the expressions swap(t, u) and swap(u, t) are valid […]

    […]

    An rvalue or lvalue t is swappable if and only if t is swappable with any rvalue or lvalue, respectively, of type T.

    (Excerpts butchered from Swappable requirements [swappable.requirements] to cut down on a whole lot of irrelevant details.)

    Variables

    Did you catch that? The first bit gives requirements that match your expectations. It’s quite straightforward to turn into an actual concept†, too:

    †: as long as we’re willing to ignore a ton of details that are outside our scope

    template
    concept bool FirstKindOfSwappable = requires(Lhs lhs, Rhs rhs) {
        swap(lhs, rhs);
        swap(rhs, lhs);
    };
    

    Now, very importantly we should immediately notice that this concept supports reference variables right out of the box:

    int&& a_rref = 0;
    int&& b_rref = 0;
    // valid...
    using std::swap;
    swap(a_rref, b_rref);
    // ...which is reflected here
    static_assert( FirstKindOfSwappable );
    

    (Now technically the Standard was talking in terms of objects which references aren't. Since references not only refer to objects or functions but are meant to transparently stand for them, we’ve actually provided a very desirable feature. Practically speaking we are now working in terms of variables, not just objects.)

    There’s a very important connection here: int&& is the declared type of our variables, as well as the actual argument passed to the concept, which in turn ends up again as the declared type of our lhs and rhs requires parameters. Keep that in mind as we dig deeper.

    Coliru demo

    Expressions

    Now what about that second bit that mentions lvalues and rvalues? Well, here we’re not dealing in variables any more but instead in terms of expressions. Can we write a concept for that? Well, there’s a certain expression-to-type encoding we can use. Namely the one used by decltype as well as std::declval in the other direction. This leads us to:

    template
    concept bool SecondKindOfSwappable = requires(Lhs lhs, Rhs rhs) {
        swap(std::forward(lhs), std::forward(rhs));
        swap(std::forward(rhs), std::forward(lhs));
    
        // another way to express the first requirement
        swap(std::declval(), std::declval());
    };
    

    Which is what you ran into! And as you found out, the concept must be used in a different way:

    // not valid
    //swap(0, 0);
    //     ^- rvalue expression of type int
    //        decltype( (0) ) => int&&
    static_assert( !SecondKindOfSwappable );
    // same effect because the expression-decltype/std::declval encoding
    // cannot properly tell apart prvalues and xvalues
    static_assert( !SecondKindOfSwappable );
    
    int a = 0, b = 0;
    swap(a, b);
    //   ^- lvalue expression of type int
    //      decltype( (a) ) => int&
    static_assert( SecondKindOfSwappable );
    

    If you find that non-obvious, take a look at the connection at play this time: we have an lvalue expression of type int, which becomes encoded as the int& argument to the concept, which gets restored to an expression in our constraint by std::declval(). Or in a more roundabout way, by std::forward(lhs).

    Coliru demo

    Putting it together

    What appears on the cppreference entry is a summary of the Swappable concept specified by the Ranges TS. If I were to guess, I would say that the Ranges TS settled on giving the Swappable parameters to stand for expressions for the following reasons:

    • we can write SecondKindOfSwappable in terms of FirstKindOfSwappable as given by the following nearly:

      template
      concept bool FirstKindOfSwappable = SecondKindOfSwappable;
      

      This recipe can be applied in many but not all cases, making it sometimes possible to express a concept parametrised on types-of-variables in terms of the same concept parametrised on expressions-hidden-in-types. But it’s usually not possible to go the other way around.

    • constraining on swap(std::forward(lhs), std::forward(rhs)) is expected to be an important enough scenario; off the top of my head it comes up in business such as:

      template
      void client_code(Val val, It it)
          requires Swappable
      //                           ^^^^^^^^^^^^^--.
      //                                          |
      //  hiding an expression into a type! ------`
      {
          ranges::swap(val, *it);
      }
      
    • consistency: for the most part, other concepts of the TS follow the same convention and are parametrised over types of expressions

    But why for the most part?

    Because there is a third kind of concept parameter: the type that stand for… a type. A good example of that is DerivedFrom() which value does not give you valid expressions (or ways to use variables) in the usual sense.

    In fact, in e.g. Constructible() the first argument Arg can arguably be interpreted in two ways:

    • Arg stands for a type, i.e. taking constructibility as an inherent property of a type
    • Arg is the declared type of a variable being constructed, i.e. the constraint implies that Arg imaginary_var { std::declval()... }; is valid

    How should I write my own concepts?

    I’ll conclude with a personal note: I think the reader should not conclude (yet) that they should write their own concepts the same way just because concepts over expressions appear, at least from the perspective of a concept writer, to be a superset of concepts over variables.

    There are other factors at play, and my concern is namely with usability from the perspective of a concept client and all these details I only mentioned in passing, too. But that doesn’t really have to do with the question and this answer is already long enough, so I’ll leave that story for another time.

提交回复
热议问题