2012-10-27 42 views
10

不是編譯我試圖編譯從here採取了以下代碼,但我得到一個編譯錯誤。有沒有人有任何想法可能是錯誤的?的std ::功能在VS2012

代碼

#include <iostream> 
#include <functional> 

struct Foo { 
    Foo(int num) : num_(num) {} 
    void print_add(int i) const { std::cout << num_+i << '\n'; } 
    int num_; 
}; 


int main() 
{ 
    // store a call to a member function 
    std::function<void(const Foo&, int)> f_add_display = &Foo::print_add; 
    Foo foo(314159); 
    f_add_display(foo, 1); 
} 

編譯錯誤:

Error 1 error C2664: 'std::_Func_class<_Ret,_V0_t,_V1_t>::_Set' : 
cannot convert parameter 1 from '_Myimpl *' to 'std::_Func_base<_Rx,_V0_t,_V1_t> *' 

感謝。

+1

@jogojapan:'print_add'有兩個參數,它有一個_implicit_'this' 'Foo const *'類型的參數也是如此。 –

+0

@ K-ballo對不起。 – jogojapan

+0

@ K-BALLO:如果它的第一個參數類型是(參考/指針)類型的構件的'的std :: function'自動使用'的std :: mem_fn'。 – Xeo

回答

7

這看起來像在VS2012中的錯誤,我做了一個錯誤報告here

現在以下工作:

編輯:編輯的基礎上XEO的建議,使用std ::的mem_fn

#include <iostream> 
#include <functional> 

struct Foo { 
    Foo(int num) : num_(num) {} 
    void print_add(int i) const { std::cout << num_+i << '\n'; } 
    int num_; 
}; 

int main() 
{ 
    // store a call to a member function 
    std::function<void(const Foo&, int)> f_add_display = std::mem_fn(&Foo::print_add); 
    Foo foo(314159); 
    f_add_display(foo, 1); 
} 
+2

你的代碼有點奇怪。你綁定'foo'並且仍然有'std :: function '。這個工作的唯一原因是因爲'std :: bind'吞下不需要的參數。與你在問題中嘗試的正確等價的東西是使用'std :: mem_fn(&Foo :: print_add)'。 – Xeo

+0

@Xeo何時應該使用std :: bind vs std :: mem_fn? std :: mem_fn看起來更簡單。 –

+0

'std :: mem_fn'是成員指針的一個簡單包裝,它返回一個函數對象,該對象將指針或對該類的引用作爲其第一個參數,然後從成員函數(如果有)接收每個參數。 'std :: bind'用於綁定參數到一個函數。 – Xeo