我有一个 C++ 程序,它将对象存储在一个向量中,然后用于std::for_each在每个对象上调用一个函数。std::for_each如果被调用的函数需要带参数,我不明白如何编写循环。
这是我想要工作的代码示例:
#include <vector>
#include <algorithm>
#include <functional>
class BaseClass
{
public:
virtual void Setup() = 0;
virtual void DisplayText(int key, int x, int y) = 0;
};
class A: public BaseClass
{
public:
void Setup();
void DisplayText(int key, int x, int y);
};
class B: public BaseClass
{
public:
void Setup();
void DisplayText(int key, int x, int y);
};
void demo(A *a, B *b, std::vector<BaseClass*>& storageVector)
{
storageVector.push_back(a);
storageVector.push_back(b);
std::for_each (storageVector.begin(), storageVector.end(),
std::mem_fn(&BaseClass::Setup));
std::for_each (storageVector.begin(), storageVector.end(),
std::mem_fn(&BaseClass::DisplayText));
}
Run Code Online (Sandbox Code Playgroud)
我从编译器得到这些错误:
error C2064: term does not evaluate to a function taking 1 arguments
error C2752: 'std::_Result_of<_Fty,_V0_t,_V1_t,_V2_t,_V3_t,_V4_t,
_V5_t,<unnamed-symbol>,_Obj>' : more than one partial
specialization matches the template argument list
Run Code Online (Sandbox Code Playgroud)
如果我尝试将参数传递给函数,例如
for_each (storageVector.begin(), storageVector.end(),
std::mem_fn(&BaseClass::DisplayText(0,0,0)));)
Run Code Online (Sandbox Code Playgroud)
然后我也得到
error C2352: 'BaseClass::DisplayText' :
illegal call of non-static member function
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
该函数DisplayText需要三个未提供的附加参数。您需要:
更改DisplayText为不需要任何参数
或者使用提供它们的 lambda:
for_each(storageVector.begin(), storageVector.end(),
[](BaseClass* c){ c->DisplayText(key, x, y); });
Run Code Online (Sandbox Code Playgroud)
或者使用提供它们的 for-each 循环:
for (auto c : storageVector)
c->DisplayText(key, x, y);
Run Code Online (Sandbox Code Playgroud)
或者将参数绑定到函子:
for_each(storageVector.begin(), storageVector.end(),
std::bind(std::mem_fn(&BaseClass::DisplayText), _1, key, x, y));
Run Code Online (Sandbox Code Playgroud)