gpt4 book ai didi

c++ - 匹配 bool vs const void* 重载的函数的地址

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:04 30 4
gpt4 key购买 nike

我正在阅读 Unexpected value using random number generator as a function in C++并且评论和当前答案说用户正在输出函数的地址。这听起来很合理。我假设发生了一个函数到指针的转换,因此与 const void* 重载相匹配,但是在我自己测试之后,我在 GCC/Clang 和 GCC/Clang 中得到了不同的结果MSVC。以下测试程序:

#include <iostream>

void test()
{
}

void func(bool)
{
std::cout << "bool";
}

void func(const void*)
{
std::cout << "const void*";
}

int main()
{
func(test);
}

在 GCC/Clang 中输出 bool ( coliru )

MSVC 中的

const void*( rextester 警告实时协作链接)

N3337说:

[卷积函数]

An lvalue of function type T can be converted to a prvalue of type "pointer to T." The result is a pointer to the function.

[转换 bool ]

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

所以不是空指针值的指针转换为 bool 应该等于 true,解释 GCC/Clang 给出的警告。

然后 [over.ics.scs] 下的表 12 转换为函数到指针的转换提供了“精确匹配”等级和 bool 转换“转换”等级。 [over.ics.rank]/4 然后说:

Standard conversion sequences are ordered by their ranks: an Exact Match is a better conversion than a Promotion, which is a better conversion than a Conversion. Two conversion sequences with the same rank are indistinguishable unless one of the following rules applies:

— A conversion that does not convert a pointer, a pointer to member, or std::nullptr_t to bool is better than one that does.

— [...]

我不是语言律师,所以我希望我引用了正确的部分。

但是 MSVC 将调用 const void* 重载,即使 bool 重载不存在,反之亦然:GCC/Clang 将调用 bool 重载,即使 const void* 重载不存在。所以我不清楚这里的转换。有人可以帮我解决这个问题吗?

最佳答案

似乎是 MSVC 中的错误(或扩展)。该标准未定义从“指向函数的指针”到“指向 void 的指针”的任何标准转换。

很难为某物的缺失提供引述,但我能做的最接近的是 C++11 4.10/2 [conv.ptr]:

A prvalue of type “pointer to cv T,” where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a “pointer to cv T” to a “pointer to cv void” points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject). The null pointer value is converted to the null pointer value of the destination type.

连同 3.9/8 [basic.types]:

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.

(强调我的)

使用 /Za禁用扩展将禁用非标准转换。

关于c++ - 匹配 bool vs const void* 重载的函数的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27226680/

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