2

I have a string-like class that is implicitly convertible to string_view. This works in almost all cases, but not for ostream inserters, where I need to explicitly write an ostream inserter for my class. Equivalent case for an object convertible to an int does work for ostream.

I am guessing the reason is that string_view (and hence the ostream inserter) are templates, but can someone explain in more detail why this fails to compile?

#include <iostream>
#include <string_view>

struct I {
    operator int() const { return 4; }
};
struct S {
    operator std::string_view() const { return "I am an S"; }
};

int main() {
    I i;
    S s;
    std::cout << i;  // Works
    std::cout << s;  // Doesn't
}

See Godbolt

7
  • 1
    Always post complete error along with your question. Commented Jul 19, 2024 at 9:23
  • 1
    Just use cout << static_cast<string_view>(s); Commented Jul 19, 2024 at 9:26
  • Another instance of: Why does the implicit type conversion not work in template deduction?. Also Cannot std::cout an implicitly converted std::string Commented Jul 19, 2024 at 9:30
  • Adding the missing colon, and the remaining error is a failure to find a candidate match for cout << s. Commented Jul 19, 2024 at 9:31
  • 1
    One solution is of course to add an operator<< for S that does the casting for you. (Or just writes the text, if that is the only use for the conversion). Commented Jul 19, 2024 at 10:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.