我有一个C++程序,它将对象存储在一个向量中,然后使用std::for_each
在每个对象上调用一个函数。如果被调用函数需要参数,我不明白如何编写std::for_each
循环。如何调用具有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));
}
我从编译器得到这些错误:
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
如果我试图传递参数的功能,例如
for_each (storageVector.begin(), storageVector.end(),
std::mem_fn(&BaseClass::DisplayText(0,0,0)));)
然后我也得到
error C2352: 'BaseClass::DisplayText' :
illegal call of non-static member function
我缺少什么?
错误往往带有行号。你的是否这样做?他们对应哪条线? – 2015-02-10 16:52:08
在第二个for_each循环中,DisplayText方法应接收声明中公布的3个参数。也许这是一个问题。 – average 2015-02-10 16:56:17
@MarcusMüller它说错误在文件xrefwrap中。绝对是一个我没有碰到的文件。在我的源代码中编写了所有这些.cpp – SyntaxIsEvil 2015-02-10 16:57:44