Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Null<std::string>

Tags:

c++

templates

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==
}
like image 358
Michael Avatar asked Apr 22 '26 15:04

Michael


1 Answers

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==.

like image 176
M.M Avatar answered Apr 24 '26 04:04

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!