c++ - Null<std::string> 问题

标签 c++ templates

我在 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/

相关文章:

templates - 是否可以创建新的工作表并将文件中的数据添加到其中?

c++ - Boost.Hana JSON 示例:string 和 decltype(std::to_string(...)) 之间的区别

c++ - 将大型成员对象移出类?

c++ - 在 Qt 中将 QString 转换为 Ascii 值,反之亦然

c++ - 在测试已声明但未定义的运算符是否存在时,static_assert 真的应该成功吗?

c++ - 我的 C++ 代码在宏+模板编译时失败,为什么会出现这个错误?

c++ - 具有模板实例化的模板静态库

c++ - 无法通过空格将文本文件行分隔为 vector

c++ - 在哪种情况下 UDP 套接字上的 sendto() 返回 0?

c++ - <函数名称> 的 undefined reference