微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

NULL 隐式指针转换导致不明确的重载

如何解决NULL 隐式指针转换导致不明确的重载

有问题的 C++03 代码

#include <cstddef>
struct Foo {
    explicit Foo(const char *){}
    Foo &operator=(const char *) {return *this;}
    Foo &operator=(char) {return *this;}
};
int main() {
    Foo s("foobar");
    s = NULL;
}

错误

In file included from /opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/cstddef:50,from <source>:1: <source>: In function 'int main()': <source>:9:9: error: ambiguous overload for 'operator=' (operand types are 'Foo' and 'long int')
    9 |     s = NULL;
      |         ^~~~ <source>:4:10: note: candidate: 'Foo& Foo::operator=(const char*)'
    4 |     Foo &operator=(const char *) {return *this;}
      |          ^~~~~~~~ <source>:5:10: note: candidate: 'Foo& Foo::operator=(char)'
    5 |     Foo &operator=(char) {return *this;}
      |          ^~~~~~~~

如果我理解正确,问题的根源在于 C++03 中的 NULL 既可以充当整数又可以充当指针。我也知道 C++11 及更高版本提供 nullptr解决这个问题。升级到 C++11 不是我的选择。

问题:这个问题在实践中是如何解决的,如何保持提供重载的能力?

一种方法是告诉用户不要使用NULL。有程序化的解决方案吗?

解决方法

实现它的一种方法是为 char 使用代理结构,这将使 operator=(const char*) 更受欢迎。像这样:

#include <cstddef>

struct MyChar
{
    MyChar(char c) : c(c){}
    operator char() {return c;}
    char c;
};

struct Foo {
    explicit Foo(const char *){}
    Foo &operator=(const char *) {return *this;}
    Foo &operator=(MyChar) {return *this;}
};
int main() {
    Foo s("foobar");
    s = NULL;
    s = 'x';
    s = "foo";
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。