我有一個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