2016-10-07 28 views
10

假设我有一个constexpr函数指针数组,我想编写一个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); 

现在这个代码编译铛上和MSVC,但GCC将只编译时FindMatchingIdx被调用数组中的第一个元素。如果FindMatchingIdx被调用test1,GCC将编译代码,但是如果FindMatchingIdx被调用test2test3 GCC将无法编译代码,给人的错误消息:

error: '(test1 != test2)' is not a constant expression.

如果FindMatchingIdx有递归,GCC将未能将其视为constexpr函数。这是GCC中的错误吗?函数指针比较如何在constexpr函数内工作?显然,它不能使用实际指针值,因为链接器会指定这些值。

工作例如:https://godbolt.org/g/xfv1PM

+0

它看起来像一个bug,可能是'operator!=(T,T)',其中'T'是一个函数指针不是'constexpr'而'operator ==(T,T)'它是。 – 101010

回答

2

我不知道这是为什么GCC抱怨,但在标准样,如果test1test2有不同的地址,因此比较相等some arguable ambiguity

如果标准在那里实际上是模棱两可的,那么gcc正确地说test1 != test2是标准没有指定的。同时,test1==test1由标准规定。

函数指针的不等式具有这样的好处,它允许编译器使用相同的二进制实现将相同地址分配两个不同的函数。因此,test1test2test3将是具有相同地址的不同函数,并且指向它们的指针会相等。

相关问题