【问题标题】:How to give a member function as a parameter?如何将成员函数作为参数?
【发布时间】:2015-07-14 14:38:45
【问题描述】:

我正在为 C++ 模板、函数和绑定而苦苦挣扎。

假设我的班级A 是这样的:

class A {
    void set_enabled_for_item(int item_index, bool enabled); 

    void set_name_for_item(int item_index, std::string name); 

    int item_count();
}

我想像这样在A 创建一个方法:

    template <typename T>
    void set_for_all_items(T value, ??? func) {
        auto count = trackCount();
        for (auto i = 0; i < count; ++i) {
            func(i, value);
        }
    }

所以我可以在参数中使用 A 的成员函数来调用它,就像这样(或类似的东西):

auto a = new A;
a->set_for_all_items("Foo Bar", &A::set_name_for_item);

三个??? 将是第二个参数的类型。由于我对 std::function、std::bind 和模板还很陌生,所以我尝试了我已经知道可以使用的方法,但总是遇到编译错误。

那该怎么做呢?

【问题讨论】:

    标签: c++ std-function


    【解决方案1】:

    标准成员函数的语法是Ret (Class::*) (Args...)。在您的情况下,这可能看起来像这样(未经测试):

    template <typename T, typename Arg>
    void set_for_all_items(T value, void (A::* func) (int, Arg)) {
        auto count = trackCount();
        for (auto i = 0; i < count; ++i) {
            (this->*func)(i, value); //note the bizarre calling syntax
        }
    }
    

    这将允许您使用所需的语法进行调用:

    auto a = new A;
    a->set_for_all_items("Foo Bar", &A::set_name_for_item);
    

    如果您想使用std::function,则需要使用 lambda 或 std::bind 或类似方法使用隐式对象参数来包装您的成员函数。

    【讨论】:

    • 由于转换原因,您的两种独立类型的解决方案更好:+1
    • 完美!奇怪的调用语法是我所缺少的!谢谢您的帮助。只要允许,我就会接受答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2013-06-29
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多