首页 > 解决方案 > 如何从调用表达式中获取函数的类型?

问题描述

我想进行单元测试以检查(并了解函数解析的工作原理),对于在某些数学函数中为原始类型采用左值而不是 const 左值引用的函数重载,正在调用好的函数。我没有发现任何关于它的常见模式。

struct A {/* ... */};

A f(A) {} // #1
A&& f(A&&) {} // #2
// Or some very complicated template overloading

int main() {
    f(A()); // call #2 ; How to get it ?
}

// I want to have:
// typeid(f).name();

是否可以在编译时typeid(f)获取?context(就像 gcc 的抱怨一样)

“伪代码”:

std::cout << typeid(f with args A()).name() << std::endl 
// >> "A&& f(A&&)"   (#2)

只有typeid(f),编译器(Ubuntu x64 上的 gcc 7.3.0)

/home/xyzz/project/tests/RunTests.cpp:22: erreur : overloaded function with no contextual type information
     typeid(tst).name();
            ^~~

typeid(f())它实际上返回返回类型

推荐答案: std::result_of。模板参数没有rebuild,但我们可以得到函数类型。

标签: c++c++11

解决方案


以下似乎适用于我的机器。离你想要的有多近?

    std::cout
      << typeid( static_cast<void (*)(A)>(f) ).name() << std::endl;

推荐阅读