从(成员)函数推导类型

Deduce type from (member) function

本文关键字:类型 函数 成员      更新时间:2023-10-16

有没有一种简单的方法来推导成员函数的"类型"?我想推导以下(成员)函数的类型:

struct Sample {
  void func(int x) { ... }
};
void func(int x) { ... }

至以下类型(用于std::function):

void(int)

我正在寻找一个支持变量计数(而不是varargs!)参数的解决方案。。。

EDIT-示例:

我正在寻找一个类似于decltype的表达式,我们称之为functiontype,它具有以下语义:

functiontype(Sample::func) <=> functiontype(::func) <=> void(int)

CCD_ 4应计算为与CCD_ 5兼容的类型。

这有帮助吗?

#include <type_traits>
#include <functional>
using namespace std;
struct A
{
    void f(double) { }
};
void f(double) { }
template<typename T>
struct function_type { };
template<typename T, typename R, typename... Args>
struct function_type<R (T::*)(Args...)>
{
    typedef function<R(Args...)> type;
};
template<typename R, typename... Args>
struct function_type<R(*)(Args...)>
{
    typedef function<R(Args...)> type;
};
int main()
{
    static_assert(
        is_same<
            function_type<decltype(&A::f)>::type, 
            function<void(double)>
            >::value,
        "Error"
        );
    static_assert(
        is_same<
            function_type<decltype(&f)>::type, 
            function<void(double)>
            >::value,
        "Error"
        );
}