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?
<code>#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
}
</code>
<code>#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
}
</code>
#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
6