How to encode and overload a function that returns itself? C ++ 17

Using msvc last (since 25DEC17).

    template< typename T>
    auto out_ (const T & val_) 
    {
        // do something with val_

        // error: can not deduce auto from out_
        return out_;
    }

The question is how to encode and then write a few overloads of this little โ€œthingโ€ above?

Yes, it must be msvc and C ++ 17. GCC 7.0.2 does not compile this. clang have not tried it yet.

Perhaps the functor pattern might help?

Please advise...

+4
source share
2 answers

I am surprised that your lambda solution works with g ++. clang ++ complaints using

 error: variable 'out_' declared with deduced type 'auto' cannot appear in its own initializer
 return out_ ;
        ^

I suspect that this is the correct clang ++ refusing your code (and the wrong g ++ accepting it), but I'm not sure.

Anyway, I find the idea that lambda is getting interesting.

- ( , ) operator() .

struct outS
 {
   template <typename T>
   outS const & operator() (T const & t) const
    {
      std::cout << t;

      return *this;
    }
 };

, , ,

outS{}("Hello ")("from ")("GCC ")(__VERSION__)(" !");

std::endl .

, std::endl (. CPP)

template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );

std::endl .

std::cout << std::endl;

std::wcout << std::endl;

<< std::endl; outS

outS{}(std::endl);

outS std::endl.

, ; std::endl std::cout, std::endl char std::char_traits<char>.

, (, )

outS{}(std::endl<char, std::char_traits<char>>);

struct (outS), endl()

outS const & endl () const
 {
   std::cout << std::endl;

   return *this;
 }

outS{}.endl();

#include <iostream>

struct outS
 {
   template <typename T>
   outS const & operator() (T const & t) const
    {
      std::cout << t;

      return *this;
    }

   outS const & endl () const
    {
      std::cout << std::endl;

      return *this;
    }

 };

int main()
 {
   outS{}("Hello ")("from ")("GCC ")(__VERSION__)(" !").endl();
 }
+2

. + :

#include <iostream>

    auto out_ = [] ( auto & val_) 
    {
        std::cout << val_;
        return out_ ;
    };

   int main()
   {
    out_("Hello ")("from ")("GCC ")(__VERSION__)(" !"); 
    // GCC can not compile this: ( std::endl );
   }

, , . GCC 7.0.2 std:: endl, .

http://coliru.stacked-crooked.com/a/b85b5f89047b5828

std:: endl "problem" @max66, , ++ 20 / lambdas, "auto" "auto"...

, jQuery, , " "... . .

( ++ 11) @max66. ++ 17 ( ) , .

, ...

https://dbj.org/callstream-project-euler/

0

Source: https://habr.com/ru/post/1691319/


All Articles