Null<std::string> 的问题

Issue with Null<std::string>

本文关键字:问题 gt std lt Null string      更新时间:2023-10-16

我在 Null 类下面设计了泛型编程,我可以做一些类似 T A=Null() 的事情,除了 std::string,编译器找不到合适的运算符 == 并给我很多错误。问题是为什么其他类型可以正常工作?我做错了什么?

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

这里使用的==实际上是:

template< class CharT, class traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, 
             const basic_string<CharT,Traits,Alloc>& rhs );

用户定义的转化序列不考虑模板类型推断,因此无法在此处(或其他)推断出CharT参数。

要解决此问题,您可能需要定义自己的非模板operator==