簡體   English   中英

如何在Visual Studio 2008 SP1中使用std :: tr1 :: mem_fun?

[英]How do I use std::tr1::mem_fun in Visual Studio 2008 SP1?

VS2008 SP1文檔討論了std::tr1::mem_fun

那么,為什么當我嘗試使用std::tr1::mem_fun ,為什么會出現此編譯錯誤?:

'mem_fun' : is not a member of 'std::tr1'

同時,我可以毫無問題地使用std::tr1::function

這是我嘗試編譯的示例代碼,應該通過function<void (int)>Test的實例上調用TakesInt

#include "stdafx.h"
#include <iostream>
#include <functional>
#include <memory>

struct Test { void TakesInt(int i) { std::cout << i; } };

void _tmain() 
{
    Test* t = new Test();

    //error C2039: 'mem_fun' : is not a member of 'std::tr1'
    std::tr1::function<void (int)> f =
        std::tr1::bind(std::tr1::mem_fun(&Test::TakesInt), t);
    f(2);
}

我正在嘗試使用tr1版本的mem_fun ,因為使用std::mem_fun我的代碼也不會編譯! 我無法從編譯器錯誤中分辨出問題出在我的代碼上,還是可以通過使用tr1的mem_fun 那是您的C ++編譯器錯誤(或者也許就是我!)。


更新:對。 答案是將其正確拼寫為mem_fn!

但是,當我解決該問題時,代碼仍然無法編譯。

這是編譯器錯誤:

error C2562: 
'std::tr1::_Callable_obj<_Ty,_Indirect>::_ApplyX' :
  'void' function returning a value

更改為此:

std::tr1::function<void (int)> f =
    std::tr1::bind(std::tr1::mem_fn(&Test::TakesInt), t, std::tr1::placeholders::_1);
f(2);

活頁夾需要int參數。 因此,您必須為其指定一個占位符,以代表生成的函數對象所需的整數參數。

順便說一句:我不確定你是否已經知道這一點。 但是您不需要那個mem_fn。 只需將其更改為

std::tr1::function<void (int)> f =
    std::tr1::bind(&Test::TakesInt, t, std::tr1::placeholders::_1);
f(2);

我既不是TR1還是VS2008的專家,但是快速瀏覽一下一下,可以發現您正在尋找的函數是std :: tr1 :: mem_fn。 (至少,Boost在其TR1實現中就是這樣稱呼的,這就是它在Wikipedia上的詳細說明。)

我不知道為什么舊版本的mem_fun會出現編譯錯誤。 如果您發布有關此問題的編譯器消息,則可能有助於我們弄清楚該消息。

要像這樣使用mem_fun,您需要完全指定所有模板參數(因為mem_fun是一個類,並且自動對類進行模板參數推導)。 另外,mem_fun僅具有采用0個參數的默認構造函數。

沒有完整的類定義,很難正確。
但我對您想要的最好的選擇是:(或接近)

 std::tr1::mem_fun<Test,void (Test::*)(Test*),&Test::TakesInt>()

我認為您正在尋找的是mem_fn()。 此函數返回類型為mem_fun的對象。 由於它是一種功能,因此可以自動進行模板參數推導。

  std::tr1::mem_fn(&Test::TakesInt)

要解決第二個問題,請使用:std :: bind1st()

  f=    std::bind1st(std::tr1::mem_fn(&Test::TakesInt), t);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM