【问题标题】:for each call function with member function pointer and parameters对于每个调用函数,带有成员函数指针和参数
【发布时间】:2023-04-07 18:05:02
【问题描述】:

我做了一个模板列表的简单实现:

template<typename T>List{
    [...]
private:
    class ListElement{
        ListElement * next;
        T* value;
    };
    ListElement *first, *last;
};

现在我希望能够编写一个“为每个调用”方法,它接受一个指向 T 类型的成员函数的函数指针,并为每个项目调用该函数,并且还可以将任意参数传递给这些函数调用,例如:

List<Item> list = new List<Item>();
[...]
list.for_each_call(&Item::update, time_passed);

通过调用update(int time_passed) 方法来更新列表中的每个项目。

我可以通过实现这个来解决这个问题:

void List<T>::for_each_call(void (*func) (T*)){
    for(ListElement * current = this->first; current != nullptr; current = current->next)
         func(current->value);
}

每次我想对每个存储的值调用一个方法时,我都会用这样的方式调用该函数:

void call_update(Item* item){
    item->update(globally_set_update_value_before_calling_for_each);
}

但是我已经创建了 8 种不同的全局定义的“call_X”方法,这开始变得烦人了。

我可以实现我上面描述的吗? Lambda 表达式在这里也可以很好地使用。

是的,我正在尝试明确解决任何 std:: 的问题,看看如果没有它,我如何自己实现它。

【问题讨论】:

    标签: c++ lambda member-function-pointers


    【解决方案1】:

    您对“将任意参数也传递给这些函数调用的可能性”的要求几乎需要使用模板和参数包。

    template<typename func_type, typename ...Args>
    void for_each_call(func_type &&func, Args && ...args)
    {
        for(ListElement * current = first; current != nullptr; current = current->next)
             func(current->value, std::forward<Args>(args)...);
    }
    

    【讨论】:

    • 你不应该需要参数...如果你传递一个 lambda。
    • 你不知道,但这也应该适用于普通函数指针。
    • 该解决方案也使用 std::forward ,这很糟糕,因为我不想使用 std:: --- 这是我自制练习的重点
    • 我怎么称呼这个?
    • for_each_call(lambda/class/functionptr [, any extra arguments>]*)
    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2012-12-16
    • 2012-10-03
    相关资源
    最近更新 更多