我想知道比较(不仅是 ==
和 !=
)函数指针是否合法,如果两个函数具有相同的类型或转换为 无效*
。
这里是一些示例代码:
#include <iostream>
struct A { static void f(){} };
struct B { static void f(){} };
int main()
{
std::cout << reinterpret_cast<void*>(&A::f) << '\n';
std::cout << reinterpret_cast<void*>(&B::f) << '\n';
std::cout << (&A::f < &B::f) << '\n';
}
GCC ( http://coliru.stacked-crooked.com/a/c03b2d2dc528c197 ) 和 Clang ( http://coliru.stacked-crooked.com/a/3330f8e0b88cc523 ) 似乎没问题。
有人可以指出标准中的正确段落吗?
谢谢!
最佳答案
您的示例可能无法编译。如果确实编译,则不能保证按预期工作。但在实践中,它可能会。
从 C++11 开始,函数指针到对象指针的转换是有条件地支持实现定义的结果。有条件支持意味着实现可以选择是否要支持它。如果他们不这样做,他们可能只会发出一条错误消息。
对于支持它的实现,很少能保证转换的结果:所说的只是如果它被支持,您可以将它转换回来并获得原始值。这并不意味着相等或关系比较的结果。
8 Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value.
有意义==
和 !=
比较,直接比较就可以了。
[...]
(3.2) Otherwise, if the pointers are both null, both point to the same function, or both represent the same address, they compare equal.
(3.3) Otherwise, the pointers compare unequal.
至于<
, <
的常用规则使您的比较与 int i, j; &i < &j;
一样毫无意义:
4 The result of comparing unequal pointers to objects86 is defined in terms of a partial order consistent with the following rules:
[...]
(4.3) Otherwise, neither pointer is required to compare greater than the other.
关于c++ - 函数指针的比较是否合法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101474/