允许在constexpr函数中比较Is函数指针
Is function pointer comparison in a constexpr function allowed?
假设我有一个constexpr函数指针数组,我想写一个constexpr函数来查找指定函数的数组索引。
我可能有这样的代码:
void test1(){}void test2(){}void test3(){}void test4(){}
typedef void(*func)(void);
constexpr func funcs[] = { &test1, &test2, &test3 };
constexpr int FindMatchingIdx (const func work, const int idx) {
return (work == funcs[idx]) ? (idx) : (FindMatchingIdx(work, idx + 1));
}
constexpr unsigned int loc = FindMatchingIdx (&test1,0);
现在这段代码可以在Clang和MSVC上编译,但是GCC只会在使用数组中的第一个元素调用FindMatchingIdx
时编译。如果用test1
调用FindMatchingIdx
, GCC将编译代码,但是如果用test2
或test3
调用FindMatchingIdx
, GCC将编译代码失败,给出错误信息:
error: '(test1 != test2)'不是一个常量表达式。
如果FindMatchingIdx
必须递归,GCC将无法将其视为constexpr函数。这是GCC中的一个bug吗?函数指针比较是如何在constexpr函数内工作的?显然,它不能使用真正的指针值,因为这些值是由链接器分配的。
工作示例:https://godbolt.org/g/xfv1PM
我不知道这是否是 gcc抱怨的原因,但是在标准中关于test1
和test2
是否有不同的地址,因此比较相等的问题上存在一些可争议的歧见。
如果标准在这里实际上是模棱两可的,那么gcc说test1 != test2
没有被标准指定是正确的。同时,test1==test1
由标准指定。
函数指针的不等式是这样的,它允许编译器为具有相同二进制实现的两个不同的函数分配相同的地址。因此,test1
、test2
和test3
将是具有相同地址的不同函数,并且指向它们的指针将比较相等。
相关文章:
- C++自定义比较函数
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- C++模板函数,用于比较任何无符号整数和有符号整数
- 函数类作为比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- std::max() 函数与定点实现的比较中的问题
- 如何比较两个函数的速度和性能
- 对没有比较器或λ函数的向量进行排序?
- 使用迭代器的自定义比较器函数
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 比较 n 女王的 next_permutation 函数
- 用于基于成员字段或函数创建比较器的快捷方式
- 为什么 std::stable_sort() 的比较函数的参数必须是设置常量?
- 为什么在类或结构中传递自定义比较器函数?
- 浮点数比较为什么没有相等的函数
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- 为什么函数比较器不像在排序中那样在优先级队列中工作?
- c++ STL集合的比较函数:比较函数可以是类的成员函数吗?
- 联合值的单函数比较