解决歧义的方法

Approaches on fixing the Ambiguity

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

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 参数的 "dummy" 重载来解决:

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

您可以将 nullptr_t 与另一个重载一起使用:

void Display(std::nullptr_t nullData)
{
    // Handle special case of nullptr
}