2013-02-18 95 views
0

是否有简单的方法来推导出成员函数的“类型”?我想推导出以下(成员)函数类型:(在std::function使用)为以下类型从(成员)函数中派生类型

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

void func(int x) { ... } 

void(int) 

我在寻找,做一个解决方案支持可变计数(不可变参数!)的参数...

编辑 - 例如:

我在寻找一个前类似decltype PRESSION - 我们称之为functiontype - 具有以下语义:

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

functiontype(expr)应该评估的类型,它是与std::function兼容。

+2

重载的函数会导致您的梦想。 – Xeo 2013-02-18 22:58:28

+0

@Xeo:我同意,但让我们假设这是在没有重载函数的情况下使用的... – MFH 2013-02-18 23:02:34

+0

@juanchopanza:我知道,但它的“接口”是[至少它的目的是什么] – MFH 2013-02-18 23:11:03

回答

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" 
     ); 
} 
+0

谢谢你做到了。 – MFH 2013-02-18 23:11:42

+0

@MFH:很高兴帮助。 – 2013-02-18 23:11:59

+1

再次,超载的功能会导致你的梦想。 :3 – Xeo 2013-02-18 23:21:26

相关问题