c++ - 调用 operator== 时,MSVC 不会执行用户定义的到 std::nullptr_t 的隐式转换

标签 c++ visual-c++ operator-overloading implicit-conversion

考虑以下代码:

struct X { operator std::nullptr_t() const { return nullptr; } };
X x;
assert(x == nullptr);

据我所知,它应该可以工作,因为 X 可以隐式转换为 std::nullptr_t 因此 operator== 应该执行到左参数的隐式转换。这似乎是 GCC 和 Clang 中发生的事情,它们愉快地接受了代码。 CppInsights似乎证实了隐式转换确实按预期发生了。

但是,此代码无法在 MSVC 中编译并出现以下错误 (Godbolt link)

error C2676: binary '==': 'main::X' does not define this operator or a conversion to a type acceptable to the predefined operator

这段代码是无效的、特定于实现的行为,还是 MSVC 错误地拒绝了它?

最佳答案

MSVC 拒绝代码是错误的,因为程序结构良好,因为可以通过转换运算符进行隐式转换以检查 x == nullptr

已提交相同的错误报告 here .

关于c++ - 调用 operator== 时,MSVC 不会执行用户定义的到 std::nullptr_t 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73044484/

相关文章:

c++ - WinAPI 获取对另一个应用程序控件的访问权限

c++ - Windows Phone 8 的 MP4/h264 解码库

c++ - 如何将 std::string 复制到 unsigned char 数组?

c++ - XML - SelectNodes - 如何获取具有某些值的属性的节点 (MFC)

指针的 C++ 运算符重载

c++ - 在 Android NDK 项目中包含 ICU

c++ - 在 MFC 中创建标尺栏

c++ - 如何仅包含一次文件/防止 C++ 程序中旧 C API 中的函数重新定义

c++ - 'operator==' 具有自己的类和 std::string_view 的不明确重载

c++ - 运算符重载错误