将C ++成员函数指针传递给STL算法 [英] Passing a C++ Member Function Pointer to an STL Algorithm
问题描述
我的成员函数如下:
class XYZ{
public:
float function(float x);
private:
float m_DensityMin;
float m_DensityMax;
};
现在,我正在尝试转换 std :: vector< float>foo
使用 std :: transform
STL算法,方法是传递成员函数 function
,并将结果值存储在向量 bar
中
Now, I'm trying to transform a std::vector<float> foo
using the std::transform
STL algorithm by passing the member function function
, and storing the resulting values in a vector bar
.
如果我将该函数用作全局函数,并且应该使用随机数据来表示该类的成员变量,那么它将正常工作.
If I use the function as a global function, with random data that should denote the member variables of the class, it works fine.
但是,由于该函数需要使用类的成员变量 m_DensityMin
和 m_DensityMax
,因此我需要将其用作成员函数.这是我尝试过的:
However, as the function requires the use of member variables m_DensityMin
and m_DensityMax
of the class, I need to use it as a member function. This is what I've tried:
std::transform(foo.begin(), foo.end(), bar.begin(), &XYZ::function);
但是我最终遇到了VS2010中的错误:
but I end up with the error in VS2010:
error C2065: term does not evaluate to a function taking 1 arguments
据我所知,我只传递了一个参数.有指针吗?这是一个类似的问题,我已经尝试过使用std::mem_fun,因为std :: mem_fn对我不可用,但无济于事.
As far as I can tell I'm passing only 1 argument. Any pointers? Here's a similar question, I've tried with std::mem_fun, as std::mem_fn is not available to me, but to no avail.
推荐答案
<代码> std :: mem_fun 本身仅为成员函数提供包装器,因此将在传递给其 operator()
的第一个参数的上下文中调用该包装器.话虽如此,您需要绑定 的正确实例XYZ
,然后再将函数对象传递到 std :: transform
算法:
std::mem_fun
itself only povides a wrapper for a member function, so that one will be invoked in the context of the first argument passed to its operator()
. Having said that, you need to bind the proper instance of XYZ
prior to passing the function object to the std::transform
algorithm:
XYZ xyz;
std::transform(foo.begin(), foo.end(),
std::back_inserter(bar),
std::bind1st(std::mem_fun(&XYZ::function), &xyz));
// ~~~~~~^ ~~~~~~^ ~~~^
这篇关于将C ++成员函数指针传递给STL算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!