我在 Null 类下面设计了泛型编程,我可以做一些类似 if 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==
。
关于c++ - Null<std::string> 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631432/