Perfect pass-through

前端 未结 1 675
谎友^
谎友^ 2021-02-05 16:16

I\'m thinking about a problem which has some similarity with perfect forwarding, but where the function argument is not passed to a called function, but returned. This is why I

1条回答
  •  臣服心动
    2021-02-05 17:14

    std::ostringstream() is an rvalue, but operator<< takes an lvalue as first argument

    There's a generic inserter to take rvalue streams, but it returns a basic_ostream&:

    template 
      basic_ostream&
      operator<<(basic_ostream&& os, const T& x);
    

    To work correctly for your example it would have to return the derived type of the stream (std::ostringstram).

    1. Is the output operator as I wrote it indeed working as expected (and fulfilling all the requirements I gave)? Or could it fail in unexpected ways or have other unexpected consequences? Especially: Is my use of std::forward correct here?

    Your code looks correct to me.

    1. Is there an easier way to meet the requirements?

    Your code looks similar to the code I wrote to solve this problem (see below).

    1. Assuming this is indeed correct and the simplest way to do it: Do you consider it a good idea to do that, or would you advice against it (both specifically for stream output as in my example, and as a more general scheme for passing objects through functions)?

    The idiom looks fine to me.

    In libc++ I defined the rvalue ostream inserter like the following (as an extension). I made an attempt to get it standardized but it was late and the committee was understandably not in the mood for more thrashing:

    template 
    inline
    typename enable_if
    <
        !is_lvalue_reference<_Stream>::value &&
        is_base_of::value,
        _Stream&&
    >::type
    operator<<(_Stream&& __os, const _Tp& __x)
    {
        __os << __x;
        return std::move(__os);
    }
    

    Unlike yours, this only accepts rvalue streams. But like yours, it returns the concrete derived type, and so works with your example.

    0 讨论(0)
提交回复
热议问题