c++ - 使用 std::function 在对象列表上调用任何对象成员函数

标签 c++ c++11 std-function stdbind

我有一个对象列表,我需要在其中调用成员函数 - 到目前为止没什么大不了的:遍历列表,进行调用 - 完成。

现在我有很多地方在同一个列表上几乎做同样的事情,除了被调用的成员函数改变(参数总是相同的,一个 double 值)。

我尝试了一些 std::function,但最终无法正常工作。有什么建议么? (我在使用 C# 多年后又回到了 C++,所以忘记了很多)。

现在是这样的:

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

这就是我喜欢的方式:

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

对于 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);
  }
}

关于c++ - 使用 std::function 在对象列表上调用任何对象成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47942403/

相关文章:

c++ - 重载赋值运算符还是使用默认运算符?

总结类实例时 C++ 崩溃

c++ - 是否存在函数指针未涵盖的 std::function 用例,或者它只是语法糖?

c++ - std::bind 到 void* 到 std::function

c++ - 使用 wxwidget 在 while 循环下移动多个文件

c++ - #define 在 C++ 中的效用

c++ - 将一种数据类型的 vector 复制到相同数据类型的结构体 vector 中的有效方法是什么?

C++:多行字符串常量中的行尾是否有标准定义?

c++ - final 用于 C++ 中的优化吗?

c++ - 从 extern 函数构造 std::function 给出 std::bad_function_call