[英]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.