2012-11-30 55 views
2

我用下面的代碼去檢測給定函數的長參數。檢測功能參數類型

因此,考慮到:

int f(int *) { return 0; } 

我想提取int *

這裏是我的嘗試:

template<class T, class U> struct SingleArg { 
    typedef U MyArg; 
}; 

template<class T, class U> SingleArg<T, U> fT(T (*p)(U)); 

int main() { 
    std::result_of<decltype(fT(f))>::type::MyArg t; 
} 

然而,這並不工作,GCC 4.6提供了錯誤

> error: std::result_of<SingleArg<int, int*> >::type has not been 
> declared 

所以,我有兩個問題:

一)什麼是錯的上面的代碼?

b)是否有可能以任何其他方式做到這一點?

+0

「函數返回類型」, 「檢測長的說法」。你真的想要什麼? –

+0

是的。要檢測功能參數類型。將修改帖子標題 – Chubsdad

+0

你考慮過boost :: function_traits嗎? – Angew

回答

0
int f(int *) { return 0; } 

template<class T, class U> struct SingleArg { 
    typedef U MyArg; 
}; 


template<typename T> 
struct the_same_type 
{ 
typedef T type; 
}; 

template<class T, class U> SingleArg<T, U> fT(T (*p)(U)); 

int main() { 

    int k; 
    the_same_type<decltype(fT(f))>::type::MyArg t= &k; 
    return 0; 
} 
+0

謝謝。這工作太棒了!標記爲答案,因爲這是第一個正確的答案 – Chubsdad

0

這個工作對我來說:

// if you want the type 
typedef decltype(fT(f))::MyArg theType; 

// if you want the name (may need demangling depending on your compiler) 
std::cout << typeid(decltype(fT(f))::MyArg).name() << std::endl; 

對於demangling,例如見abi::__cxa_demangle

+0

不適用於我。海灣合作委員會抱怨'預期的初始值設定項' – Chubsdad

+0

好吧...我使用'蘋果鏗鏘4.0版'與'-std = C++ 11',我沒有一個C++ 11啓用g ++版本用...測試。 –

+0

感謝您的幫助 – Chubsdad

5
#include <type_traits> 

template <typename Function> 
struct arg_type; 

template <class Ret, class Arg> 
struct arg_type<Ret(Arg)> { 
    typedef Arg type; 
}; 


int f(int *) { 
    return 0; 
}; 

int main(int, char**) { 
    static_assert(std::is_same<int*, arg_type<decltype(f)>::type>::value, "different types"); 
} 
+0

謝謝。這很好用! – Chubsdad