如何静态检查可能具有或可能不具有相同签名的两个函数是否是相同的函数?

How to statically check if two functions that might or might not have the same signature are the same function?

我想静态检查两个函数是否相同。

像这样:

struct Base { void f(){} };
struct Derived1: public Base { void f(){ puts("Hey!"); } };
struct Derived2: public Base { int f(){ return 0; } };
struct Derived3: public Base {};

static_assert( &Base::f != &Derived1::f );
static_assert( &Base::f != &Derived2::f );
static_assert( &Base::f == &Derived3::f );

第二个 static_assert 编译失败,因为 Base::fDerived2::f 的签名不同:

error: comparison of distinct pointer types ('void (Base::*)()' and 'int (Derived2::*)()')
static_assert( &Base::f != &Derived2::f );
               ~~~~~~~~ ^  ~~~~~~~~~~~~

我试图将那些函数指针 static_cast 指向 void*unitptr_tvoid(Base::*)(),但编译器不允许。 reinterpret_cast 的结果不是静态的,不能出现在 static_assert.

如何进行检查?

任何 C++ 标准都可以。

在尝试 == 之前,您需要一些东西来拒绝不同的签名。

template <typename F1, typename F2>
constexpr bool same_function(F1, F2) { return false; }

template <typename F>
constexpr bool same_function(F f1, F f2) { return f1 == f2; }

See it live