[英]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 ++編譯器錯誤(或者也許就是我!)。
但是,當我解決該問題時,代碼仍然無法編譯。
這是編譯器錯誤:
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);
要像這樣使用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.