Is it possible to automatically disconnect from user type to std :: string using cout?

As in the question, if I define a string operator in my class:

class Literal {
  operator string const () {
    return toStr ();
  };

  string toStr () const;
};

and then I use it:

Literal l1 ("fa-2bd2bc3e0");
cout << (string)l1 << " Declared" << endl;

with the explicit application, everything goes right, but if I delete (the string), the compiler says that it needs the translation operator declared in std :: string. Shouldn't he automatically enter my type? SOLVED: I overload the <<operator (ostream & os, const Literal & l).

+3
source share
2 answers

No. std :: string would have to have a constructor that took Literal as an argument.

, < < Literal, .

ostream &operator <<(std::ostream &stream, const Literal &rhs)
{
    stream << (string) rhs;
    return stream;
}
+10

: toStr() operator<<. ( l1.toStr() (string)l1.)

: ,

std::ostream& operator<<( std::ostream&, std::string const& );

, . ostream string . .

// This is somewhat simplified.  For the real definitions, see the Standard
// and/or your complying implementation headers.
namespace std {
  typedef basic_string<char> string;
  typedef basic_ostream<char> ostream;

  template <typename CharT>
  basic_ostream<CharT>& operator<<(
    basic_ostream<CharT>&, 
    basic_string<CharT> const&);
}

, cout << str, str std::string, , , CharT = char.

++ (Literal - string), (CharT = char) .

+5

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


All Articles