【问题标题】:Is there a way to check function signature before calling it?有没有办法在调用之前检查函数签名?
【发布时间】:2012-01-09 03:32:32
【问题描述】:

例如这有效:

if ( typeid( int) == typeid( int) ) //...

如何对函数签名做同样的事情?

if (typeid (void (*)(void) ) == typeid( void(*)(void) ) //that of course dosn't work

我们如何检查这两个签名?

void f(int);
int x(double);

【问题讨论】:

  • 您似乎正在寻找没有问题的解决方案。
  • 为什么会想要?在运行时,我认为没有用,因为链接器已经做出了决定 - 似乎您可能正在尝试一些有替代解决方案的东西。
  • @Ignacio 我认为问题已发布
  • 不,已发布一个问题。有区别。
  • @codekiddy - 当两个专业程序员问你为什么要做某事时 - 可能有一个很好的理由。即他们都认为你的方法有误。关于您为什么认为这是一个解决方案的问题中的更多信息实际上可能会帮助人们指导您找到解决实际问题的正确解决方案。我们都确信您尝试做的并不是解决实际问题的好方法

标签: c++ function signature


【解决方案1】:

函数的类型在编译时是已知的。您可以使用is_same 比较任意类型:

#include <iostream>
#include <type_traits>

int main()
{
    typedef void(*F0)(int);
    typedef void(*F1)(int, int);

    std::cout << std::is_same<F0, F0>::value << std::endl;
    std::cout << std::is_same<F0, F1>::value << std::endl;
}

结果:

1
0

类型特征值是编译时常量,可用于模板实例化和 SFINAE。

【讨论】:

  • 我不知道这些信息在运行时会有什么用处。当然它在编译时有很多用途。
  • 这很有趣,我不知道在运行时无法确定函数签名,所以这在某种程度上有助于调试。谢谢!
【解决方案2】:

使用 typeid(foo).name()

例如:if ( typeid(func1).name() == typeid(func2).name() ) //做事

#include <cstdio>
#include <iostream>
#include <typeinfo>
using namespace std ;

void foo()
{    
}

int bar()
{   
    return 1;
}

int main(void)
{
   if (typeid(foo).name() == typeid(bar).name())
       cout<<typeid(foo).name()<<" equals "<<typeid(bar).name()<<" \n";
   else
   if (typeid(foo).name() != typeid(bar).name())
       cout<<typeid(foo).name()<<" is not equal to "<<typeid(bar).name()<<" \n";

   cout << "\nPress ENTER to continue \n\n";   cin.ignore();  // pause screen

   return 0;
}

输出:

void (__cdecl*)(void) is not equal to int (__cdecl*)(void)

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2011-04-19
    • 2010-12-24
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多