gpt4 book ai didi

c++ - 解决歧义的方法

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:45 27 4
gpt4 key购买 nike

有人要求我在不修改函数声明和调用的情况下修复以下示例。

void Display(int *nData)
{
}

void Display(float *fData)
{
}

int main()
{
int a = 5;
float b = 4.0f;

Display(&a);
Display(&b);
Display(nullptr or NULL); // Ambiguity here, as nullptr or NULL (0) can be converted implicitly by compiler to both int and float

return 0;
}

有什么想法吗?谢谢

编辑:感谢您使用带重载的 std::nullptr_t 解决此问题的答案,但是如果参数是“NULL”而不是 nullptr 怎么办?如何解决?

最佳答案

这可以通过添加一个采用 std::nullptr_t 的“虚拟”重载来解决。参数:

void Display(std::nullptr_t)
{
}

这将在传递 nullptr 时被调用。


NULL 和之前推荐的空指针 0 是有问题的,因为它们会再次引入歧义。

0 的求解很简单,只需添加另一个 重载,将一个简单的int(不是指针)作为参数。这可能也解决了 NULL 的歧义,但也可能不会。

the NULL macro 的问题是它的实现定义。它可能被扩展为nullptr。它可能被展开为0。或者它可能被扩展为其他一些整数文字,其计算结果为零,但类型未知。

例如在我当前的系统上 NULL 被定义为 0LL,即 long long int

要处理所有当前可能的空指针,您需要以下重载:

void Display(std::nullptr_t);  // For nullptr
void Display(int); // For 0 and some implementations of NULL
void Display(long); // For some implementations of NULL
void Display(long long); // For some implementations of NULL

关于c++ - 解决歧义的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45595993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com