将 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;
};

现在,我尝试通过传递成员函数 function 使用 std::transform STL 算法转换 std::vector<float> foo,并将结果值存储在向量 [=16] 中=].

如果我将该函数用作全局函数,随机数据应该表示 class 的成员变量,它工作正常。

但是,由于函数需要使用class的成员变量m_DensityMinm_DensityMax,所以我需要将其作为成员函数来使用。这是我试过的:

std::transform(foo.begin(), foo.end(), bar.begin(), &XYZ::function);

但我最终在 VS2010 中遇到错误:

error C2065: term does not evaluate to a function taking 1 arguments

据我所知,我只传递了 1 个参数。任何指针? 这是一个类似的 question,我试过 std::mem_fun,因为 std::mem_fn 对我来说不可用,但无济于事。

除非函数是static,它需要一个class的实例来调用函数。因为非静态函数应该依赖于那个 class 的内部状态。如果函数独立于 class 的状态,它可能应该是静态的。

如果您必须保留所写的 class,您可以默认构造一个 XYZ 来解决这个问题,只是为了让一个实例从中调用函数。

std::transform(foo.begin(),
               foo.end(),
               std::back_inserter(bar),
               [](float a){ return XYZ{}.function(a); });

但这感觉很老套,如果函数不依赖于 XYZ 实例的状态,并且只依赖于输入 [=15=,我更希望函数是 static ].

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算法:

XYZ xyz;

std::transform(foo.begin(), foo.end(),
               std::back_inserter(bar),
               std::bind1st(std::mem_fun(&XYZ::function), &xyz));
//                  ~~~~~~^      ~~~~~~^                  ~~~^

DEMO

lambda 版本

std::vector<float> foo;
std::vector<float> bar;
foo.push_back(1.0f);
foo.push_back(2.0f);
XYZ xyz;
std::transform(foo.begin(), foo.end(), std::back_inserter(bar), 
        [&xyz](float& a){ return xyz.function(a); });
 for ( auto & x : bar)
   std::cout<<x<<"\n";