指向具有多个对象的成员函数的指针向量

Vector of pointers to member functions with multiple objects c++

本文关键字:成员 函数 指针 向量 对象      更新时间:2023-10-16

考虑以下代码:

class A
{
public:
    void aFoo() {}
};
class B
{
public:
    void bFoo() {}
};
class C
{
public:
    void c1Foo() {}
    void c2Foo() {}
};

不管代码体系结构如何,是否有可能创建指向成员函数的指针向量,即使这些函数位于多个类中?

在这种情况下,继承不是一个解决方案,因为我们不知道我们想在一个类中使用多少函数(类C有两个函数)。但是我们知道它们都有相同的原型

不同类的成员函数具有不同的类型。因此,为了拥有任何同质容器(如std::vectorstd::array),您需要将它们包装在一些可以代表它们的值类型中(如boost::variantboost::any)。

另一方面,如果你所需要的只是一个特定类型的成员函数(例如void()),并且你不介意事先传递应该调用它们的对象,那么你可以将它们存储为std::function<void()>(对于这个特定的例子),并在将它们存储在容器中之前调用std::bind

作为一个例子,给定:

A a; B b; C c;
std::vector<std::function<void()>> vector {
    std::bind(&A::aFoo, a),
    std::bind(&B::bFoo, b),
    std::bind(&C::c1Foo, c),
    std::bind(&C::c2Foo, c)
};

你可以调用:

for (auto fn : vector)
    fn();

现场演示

我不确定你想要实现什么,所以这可能不是很有帮助,但这里无论如何。

正如其他人所说,由于原型不同,您不能为此创建std::vector。但是,您可以像这样创建std::元组:

std::tuple<void (A::*)(), void (B::*)(), void (C::*)()> x(&A::aFoo, &B::bFoo, &C::c1Foo);

假设你有一个类的实例,比如A a,那么你可以像(a.*std::get<0>(x))()一样调用这个函数。

如果您也将对象存储在元组中,那么您可以遍历它们。下面的代码将做到这一点(假设您的系统中有c++ 14和Boost)

#include <iostream>
#include <tuple>
#include <type_traits>
#include <boost/mpl/find_if.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <functional>
class A
{
public:
    void aFoo()
    {
        std::cout << "A" << std::endl;
    }
};
class B
{
public:
    void bFoo()
    {
        std::cout << "B" << std::endl;
    }
};
class C
{
public:
    void c1Foo()
    {
        std::cout << "C1" << std::endl;
    }
    void c2Foo() {}
};
// functor used by boost to iterate over the tuple
template <class Tuple>
struct functor
{
    functor(Tuple t)
    : m_tuple(t)
    {
    }
    template <class X>
    void operator()(X& x) const
    {
        using namespace boost::mpl;
        using iter = typename find_if<Tuple, std::is_same < placeholders::_1, void (X::*)()> >::type;
        using type = typename deref<iter>::type;
        return (x.*std::get<type>(m_tuple))();
    }
private:
    Tuple m_tuple;
};
template <class Tuple>
functor<Tuple> make_functor(Tuple t)
{
    return functor<Tuple>(t);
}
int main()
{
    std::tuple<void (A::*)(), void (B::*)(), void (C::*)() > x(&A::aFoo, &B::bFoo, &C::c1Foo);
    std::tuple<A, B, C> y;
    boost::fusion::for_each(y, make_functor(x));
}

现场演示在这里:http://coliru.stacked-crooked.com/a/e840a75f5b42766b