从(成员)函数推导类型

时间:2013-02-18 22:53:10

标签: c++ c++11 template-meta-programming

是否有一种简单的方法来推断成员函数的“类型”?我想推断出以下(成员)函数的类型:

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

void func(int x) { ... }

以下类型(将在std::function中使用):

void(int)

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

编辑 - 示例:

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

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

functiontype(expr)应评估为与std::function兼容的类型。

1 个答案:

答案 0 :(得分:3)

这有帮助吗?

#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"
        );
}
相关问题