简体   繁体   English

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

[英]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::fDerived2::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_tvoid(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; }

See it live现场观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "加载两个具有相同静态链接函数的共享库时使用哪个函数" - Which function is used when loading two shared libraries with same statically linked functions 在C ++中定义具有相同签名的两个函数 - Define two functions with the same signature in C++ 什么可能导致相同的SSE代码在同一个函数中运行速度慢几倍? - What might cause the same SSE code to run a few times slower in the same function? 可能导致在不同角度获得完全相同的三角函数输出的原因 - What might cause to get exactly the same output of trigonometric functions in different angles 为什么编译时浮点计算可能与运行时计算的结果不同? - Why compile-time floating point calculations might not have the same results as run-time calculations? 当同一个命名空间中有两个具有相同签名的函数时会发生什么? - What happens when there are two functions with the same signature in the same namespace? 两个错位的名称分解为相同的功能签名 - Two mangled names demangling to the same function signature 如何为具有不同签名的功能分配相同的签名? - How to assign same signature to functions with different signatures? 需要帮助编写一个 function 来检查两个 BST 是否具有相同的结构 - Need help writing a function to check if two BSTs have the same structure 如何记录函数可能抛出的所有异常? - How to document all exceptions a function might throw?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM