2012-05-15 48 views
4

我正在編寫一個大量使用咖喱對象和模板的項目。 C++ 11的新功能decltype意味着我可以開始接受不顯式定義返回類型的函數對象作爲我的函數對象的咖喱。功能對象方法對函數指針是否安全?

template<typename func_T, typename arg1_T> 
struct unary_result { 
    typedef typename std::remove_reference<typename std::remove_cv<decltype(func_T()(arg1_T()))>::type>::type type; 
}; 

給出一個函數對象:

struct foo { 
    int operator()(double) const; 
}; 

(不從std::unary_function<double, int>繼承或定義其result_type),我只是取而代之的是,返回類型可以與元函數,如提取得到它作爲unary_result<foo, double>::type,這在我當前的代碼中工作得很好(一方面,它允許相同的函數對象對於不同的參數具有不同的行爲)。

我的問題是:這將如何與函數指針交互?

我知道STL能夠交替使用函數對象和函數指針,但從來沒有真正使用過函數指針,所以我的直覺在這個領域沒有很好的開發。我也意識到這可能是埋在Boost的某個地方(如果是這種情況,我相信很快就會有人指出這一點)。

+0

你能解釋一下爲什麼你需要的'decltype'?即爲什麼不簡單地做'typedef typename std :: remove_reference :: type> :: type'? – TemplateRex

+0

這會給我'foo',但我想要的是'int'。 – masaers

+0

函數對象和函數指針都可以和()運算符一起使用。但是你永遠不能真的調用一個函數對象。它們並非真正可以互換。 – BlueWanderer

回答

3

您的unary_result應該可以在函數指針上正常工作,但在std::remove_cv之前需要額外的typename

例子:

#include <type_traits> 

template<typename func_T, typename arg1_T> 
struct unary_result { 
    typedef typename std::remove_reference<typename std::remove_cv<decltype(func_T()(arg1_T()))>::type>::type type; 
}; 

struct foo { 
    int operator()(double d) const 
    { 
     return d; 
    } 

}; 

int bar(int i){ 
    return i; 
} 

template<typename Func,typename Arg> 
typename unary_result<Func,Arg>::type do_stuff(Func f,Arg a){ 
    return f(a); 
} 

int main(){ 
    int i=do_stuff(bar,42); 
    int d=do_stuff(foo(),3.1); 
} 
+0

你可以給一個工作代碼的例子,將函數對象和函數指針都傳遞給unary_result嗎? – TemplateRex