2016-06-21 73 views
1

我有下面的代碼作爲一個實驗:C++ 11在成員函數上應用result_of,失敗了,爲什麼?

int f1() { return 0; } 

struct Bar { 
    Bar() = delete; 
    int f() { return 0; } 
    int operator()() { return 1; } 
}; 

int main() 
{ 
    decltype(f1()) x = 3;//f1() is expression 
    result_of<decltype(&f1)()>::type x1 = 3;//type+param 
    result_of<Bar()>::type x3 = 3;//type+param 
    decltype(declval<Bar>().f()) y = 4;//expression 
    decltype((((Bar*)nullptr)->*(&Bar::f))()) z = 5;//expression 

    result_of<decltype(std::mem_fn(&Bar::f))()>::type y2 = 3;//error!!!!!! 
} 

一切除了最後result_of OK: 我試圖讓返回類型的Bar::f,使用result_of

爲什麼它失敗了,以及如何糾正它?

+2

它的成員函數,它要求一個隱含的對象參數,即,'的result_of ::類型y2' –

+0

謝謝,它工作,但似乎「result_of :: type y2 = 3;」也可以通過編譯。哪一個是正確的,爲什麼BAR *仍然可以被賦予這個mem_fn? –

+0

無論您使用指針還是引用類型,它都沒有區別。這裏重要的是價值類別和簡歷資格 –

回答

0

mem_fn未指定返回類型:

 
template <class R, class T> 
unspecified mem_fn(R T::* pm) noexcept; 

在的INVOKE[func.memfn]/p1來定義:

返回:一個簡單的呼叫包裝物([func.def]fn這樣表達式fn(t, a2, ..., aN)相當於INVOKE(pm, t, a2, ..., aN)[func.require])。

其中INVOKE定義包括以下兩個項目符號[func.require]/p1

定義INVOKE(f, t1, t2, ..., tN)如下:

- (t1.*f)(t2, ..., tN)f是一個指針,指向類的成員函數Tis_base_of<T, decay_t<decltype(t1)>>::valuetrue;

- ((*t1).*f)(t2, ..., tN)f是指向類Tt1的成員函數不滿足前兩項;

也就是說,什麼mem_fn回報必須是隱含的對象參數(t1)類型的第一個參數,無論是引用或指針,例如:

std::result_of<decltype(std::mem_fn(&Bar::f))(Bar&)>::type y2; 
//           ~~~^ 

std::result_of<decltype(std::mem_fn(&Bar::f))(Bar*)>::type y2; 
//           ~~~^ 

您也可以刪除std::mem_fn共:

std::result_of<decltype(&Bar::f)(Bar*)>::type y2; 
相關問題