I designed below Null class for generic programming, and I can do something like if T A=Null(), everything works fine except for std::string, where the compiler is unable to find the proper operator == and give me a lot of errors. The issue is why other types works out all right? Something I did wrong?
struct Null
{
operator std::string() const { return std::string{}; }
operator int() const { return 0; }
};
int main() {
std::string s = "hello";
Null n;
std::cout << (0 == n) << std::endl; // works
std::cout << (n == 0) << std::endl; // works
std::cout << (s == n) << std::endl; // error: no match for operator==
}
The == in use here is actually:
template< class CharT, class traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs,
const basic_string<CharT,Traits,Alloc>& rhs );
User-defined conversion sequences aren't considered for template type deduction, so it cannot deduce the CharT parameter here (or the others).
To fix this you might have to define your own non-template operator==.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With