簡體   English   中英

如何靜態檢查可能具有或可能不具有相同簽名的兩個函數是否相同 function?

[英]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 並且不能出現在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; }

現場觀看

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM