operator std::string() const?

23,441

Solution 1

It is a conversion operator that allows the object to be explicitly or implicitly casted to std::string. When such a cast occurs, the operator is invoked and the result of the cast is the result of the invocation.

As an example of an implicit cast, suppose you had a function that accepted type std::string or const std::string&, but not the given object type. Passing your object to that function would result in the conversion operator being invoked, with the result passed to the function instead of your type.

Solution 2

It is a cast operator. Any class that defines this type can be used anywhere a std::string is required. For instance,

class Foo {
public:
    operator std::string() const { return "I am a foo!"; }
};
...
Foo foo;
std::cout << foo; // Will print "I am a foo!".

Cast operators are almost always a bad idea, since there is invariably a better way to achieve the same result. In the above case, you are better off defining operator<<(std::ostream&, const Foo&).

Share:
23,441
Johnny
Author by

Johnny

Updated on February 08, 2020

Comments

  • Johnny
    Johnny about 4 years

    Can somebody tell me what precisely

    operator std::string()
    

    stands for?

  • Martin York
    Martin York almost 14 years
    I object to the term "always", it is too absolute. I think "usually" would be a better term.
  • Alex S
    Alex S almost 14 years
    Martin, I didn't say "always". I said "almost always" which isn't absolute, and is, IMO, closer to the truth than "usually".
  • Alyoshak
    Alyoshak almost 12 years
    Loki, your own comment is too absolute. Should one always avoid the term "always", or should one usually avoid the term "always"?
  • Emmanuel M. Smith
    Emmanuel M. Smith over 11 years
    things are getting paradoxical
  • poorva
    poorva over 10 years
    dont you need to typecast foo to (string)foo ?
  • Alex S
    Alex S over 10 years
    @poorva: No, it's an implicit cast. In C++11 you can write explicit operator std::string() … to require an explicit cast.
  • emem
    emem over 8 years
    @poorva you are correct, @MarceloCantos you are wrong: you do need to cast it explicitly to string in this case, otherwise you'll get an error error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&& The reason for that is the operator<< is defined as a template function, so you must have exact match for its arguments, and the implicit cast is not relevant.
  • aafulei
    aafulei over 5 years
    Please note that the code in this answer (std::cout << foo;) simply won't compile, because as @EranMarom noted operator<< is a template function. I tried. The compiler (g++ 7.3, c++14) said error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Foo').