【问题标题】:How can I create an array of member function pointers coupled with different objects?如何创建与不同对象耦合的成员函数指针数组?
【发布时间】:2022-01-05 21:03:01
【问题描述】:

假设我有类A,函数foo(int i)和类B,函数bar(int i),以及objectA(类A)和objectB(类B) .我可以这样调用函数

objectA.foo(10);
objectB.bar(20);

我想做的是将它们作为数组arr中的函数指针并像这样调用它们

arr[0](10);
arr[1](20);

有没有办法在 C++ 中做到这一点?如果有,效率如何?

【问题讨论】:

  • @Ted Lyngmo 对不起,忘了!

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


【解决方案1】:

您可以将std::function 对象存储在您从捕获objectAobjectB 的lambda 函数创建的std::vector 中。调用 std::function 对象会产生一些开销,因此如果时间很紧迫,您必须衡量它是否足够好。

例子:

#include <functional>
#include <iostream>
#include <vector>

struct A {
    void foo(int x) { std::cout << "A::foo " << x << '\n'; }
};

struct B {
    void bar(int x) { std::cout << "B::bar " << x << '\n'; }
};

int main() {
    A objectA;
    B objectB;
    std::vector< std::function<void(int)> > arr{
        [&objectA](int x) { objectA.foo(x); },
        [&objectB](int x) { objectB.bar(x); },
    };
    arr[0](10);
    arr[1](20);
}

输出:

A::foo 10
B::bar 20

【讨论】:

    【解决方案2】:

    类似于 @ted-lyngmo 的回答,但在 C++20 中,您还可以使用 std::bind_front 为向量创建函数对象:

    int main()
    {
        A objectA;
        B objectB;
        std::vector<std::function<void(int)>> arr{
            std::bind_front(&A::foo, objectA),
            std::bind_front(&B::bar, objectB)
        };
        arr[0](10);
        arr[1](20);
    }
    

    Godbolt

    【讨论】:

    • 虽然这会复制 AB 类型的对象 - 如果您需要闭包函数的寿命比 objectAobjectB 更长,这可能是一件好事,或者如果您需要调用才能使用原始对象。要告诉它不要复制,我们可以这样做std::bind_front(&amp;A::foo, std::ref(objectA)), std::bind_front(&amp;B::bar, std::ref(objectB))
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多