有没有办法在调用之前检查函数签名?

时间:2012-01-09 03:32:32

标签: c++ function signature

例如,这有效:

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

如何对功能签名做同样的事情?

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

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

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

2 个答案:

答案 0 :(得分:3)

函数的类型在编译时是已知的。您可以使用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。

答案 1 :(得分:1)

使用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)
相关问题