【问题标题】:Is there a way to get the function type of a pointer to a member function?有没有办法获取指向成员函数的指针的函数类型?
【发布时间】:2021-12-13 20:56:16
【问题描述】:

如果你有一个指向成员函数的指针,像这样:

struct Foo {  void func() {}  };

void(Foo::*funcPtr)() = &Foo::func;

有没有办法获取函数的类型,去掉Foo::

即,

void(Foo::*)() -> void(*)()

int(Foo::*)(int, double, float) -> int(*)(int, double, float)

你明白了。

目标是让std::function 接受这样的函子:

struct Functor { void operator()(...){} }

Functor f;
std::function< magic_get_function_type< decltype(Functor::operator()) >::type > stdfunc{f};

有可能吗?

【问题讨论】:

  • FWIW,如果你有 C++17,你应该能够做到auto stdfunc = std::function{Functor{}};
  • 你也可以使用 lambdas:std::function f = []() { /*do stuff*/ };
  • @NathanOliver 哇。我不知何故得到了std::function 无法推断其模板参数的想法,因此我在过去一周试图解决不存在的问题。我过去关于 SO 的四个问题(您回答了其中一个)都围绕着这个。现在感觉有点傻。
  • @JensB 不要感觉太糟糕。这是从 C++17 开始添加到 C++ 的一个特性。有关它的更多阅读,请查阅类模板参数推导 (CTAD)

标签: c++ function types std-function


【解决方案1】:

要回答您的问题,可以使用一个简单的模板:

template <typename Return, typename Class, typename... Args>
Return(*GetSig(Return(Class::*)(Args...)))(Args...);

这定义了一个名为GetSig 的函数,它接受一个成员函数指针作为参数,本质上提取Return 类型和Args... 并将其作为非成员函数指针返回。

示例用法:

class C;
int main() {
    using FuncType = int(C::*)(double, float);
    FuncType member_pointer;
    decltype(GetSigType(member_pointer)) new_pointer;
    // new_pointer is now of type int(*)(double, float) instead of
    // int(C::*)(double, float)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 2022-12-01
    • 2017-07-27
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多