[英]How to statically check if two functions that might or might not have the same signature are the same function?
I want to statically check whether two functions are the same one.我想静态检查两个函数是否相同。
Something like this:像这样的东西:
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 );
The second static_assert
fails to compile because the signature of Base::f
and Derived2::f
differs:第二个
static_assert
无法编译,因为Base::f
和Derived2::f
的签名不同:
error: comparison of distinct pointer types ('void (Base::*)()' and 'int (Derived2::*)()')
static_assert( &Base::f != &Derived2::f );
~~~~~~~~ ^ ~~~~~~~~~~~~
I tried to static_cast
those function pointers to void*
, unitptr_t
or void(Base::*)()
, but the compiler won't let me.我试图将那些
static_cast
指针静态转换为void*
, unitptr_t
或void(Base::*)()
,但编译器不会让我这样做。 While the result of reinterpret_cast
is not static and can't appear in a static_assert
.虽然
reinterpret_cast
的结果不是 static 并且不能出现在static_assert
中。
How can I perform the check?我该如何进行检查?
Any C++ standard is fine.任何 C++ 标准都可以。
You need something to reject the different signatures before trying to ==
them.在尝试
==
它们之前,您需要一些东西来拒绝不同的签名。
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.