2013-02-18 92 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

相關問題