[英]Call any object member function on a list of objects using std::function
I have a list of objects where I need to call a member function - no big deal so far: iterate through the list, make that call - done. 我有一个需要调用成员函数的对象列表-到目前为止没什么大不了的:遍历列表,进行调用-完成。
Now I have various places that almost do the same on the same list, except that the called member function changes (argument is always the same, a double value). 现在,我在不同的位置上都有几乎相同的位置,只是被调用的成员函数发生了变化(参数总是相同,一个双精度值)。
I tried around a bit with std::function, but in the end can't get it working. 我用std :: function尝试了一下,但最终无法正常工作。 Any suggestions? 有什么建议么? (I'm back to C++ after many years of C#, so forgot a lot). (经过多年的C#工作后,我回到了C ++,所以忘记了很多)。
This is how it looks now: 现在是这样的:
void CMyService::DoSomeListThingy(double myValue)
{
for (std::list<CMyListItem*>::iterator v_Iter = myList.begin(); v_Iter != myList.end(); ++v_Iter)
{
(*v_Iter)->MethodToBeCalled(myValue);
}
}
void CMyService::DoSomeThingDifferent(double myValue)
{
for (std::list<CMyListItem*>::iterator v_Iter = myList.begin(); v_Iter != myList.end(); ++v_Iter)
{
(*v_Iter)->CallTheOtherMethod(myValue);
}
}
And this is how I'd prefer it: 这就是我更喜欢的方式:
void CMyService::DoSomeListThingy(double myValue)
{
ApplyToList(&CMyListItem::MethodToBeCalled, myValue);
}
void CMyService::DoSomeThingDifferent(double myValue)
{
ApplyToList(&CMyListItem::CallTheOtherMethod, myValue);
}
void CMyService::ApplyToList(std::function<void(double)> func, double myValue)
{
for (std::list<CMyListItem*>::iterator v_Iter = myList.begin(); v_Iter != myList.end(); ++v_Iter)
{
(*v_Iter)->func(myValue);
}
}
void CMyService::ApplyToList(void (CMyListItem::*func)(double), double myValue) {
for (auto p : myList) {
(p->*func)(myValue);
}
}
With pre-C++11 compilers: 使用C ++ 11之前的编译器:
void CMyService::ApplyToList(void (CMyListItem::*func)(double), double myValue) {
for (std::list<CMyListItem*>::iterator v_Iter = myList.begin();
v_Iter != myList.end(); ++v_Iter) {
((*v_Iter)->*func)(myValue);
}
}
You could use lambdas
您可以使用lambdas
void CMyService::ApplyToList(std::function<void(CMyListItem*, double)> func, double myValue))
{
for (std::list<CMyListItem*>::iterator v_Iter = myList.begin(); v_Iter != myList.end(); ++v_Iter)
{
func(*v_Iter, myValue);
}
}
and 和
double val;
std::function<void(A*,double)> fun1 = [=](A *th,double) {
th->foo(val);
};
std::function<void(A*,double)> fun2 = [=](A *th,double) {
th->bar(val);
};
ApplyToList(fun1, val);
ApplyToList(fun2, val);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.