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

问题描述

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

像这样:

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