2

Why this code cannot compile?

#include <string>
#include <iostream>

struct Foo
{
    operator std::string () const
    {
        return std::string("Hello world !");
    }
};

int main(void)
{
    Foo f;

    std::cout << f << "\n";
}

while this one does:

#include <string>
#include <iostream>

int main(void)
{
    std::cout << std::string("Hello world !") << "\n";
}

and this one too:

#include <string>
#include <iostream>

struct Bar
{
    operator int ()
    {
        return 42;
    }
};

int main(void)
{
    Bar b;

    std::cout << b << "\n";
}

I thought this was the same thing, because of operator std::string, but g++ does not compile neither clang++.

Boiethios
  • 38,438
  • 19
  • 134
  • 183
  • There's `template operator<<(basic_ostream&, const basic_string&)` overload that you hope would get called - but that requires template parameter deduction, and said deduction doesn't take user-defined conversions into account. As a result, that overload is not considered viable, and no other overload works out, either. – Igor Tandetnik Jun 28 '16 at 13:46
  • @IgorTandetnik Please add it as answer – Boiethios Jun 28 '16 at 13:48
  • Why is it possible I search for minutes on the site and cannot find the question was still asked? – Boiethios Jun 28 '16 at 13:50
  • 1
    you need to perform explicit cast `std::cout << (std::string)f << "\n";` – mvidelgauz Jun 28 '16 at 13:56
  • You might consider adding to Foo: "std::string operator ()() { return "Hello World 2 !"; }". Then in main, use std::cout << foo() << "\n"; But I like mvidelgauz's cast. – 2785528 Jun 28 '16 at 14:04

0 Answers0