指向具有多个对象的成员函数的指针向量
Vector of pointers to member functions with multiple objects c++
考虑以下代码:
class A
{
public:
void aFoo() {}
};
class B
{
public:
void bFoo() {}
};
class C
{
public:
void c1Foo() {}
void c2Foo() {}
};
不管代码体系结构如何,是否有可能创建指向成员函数的指针向量,即使这些函数位于多个类中?
在这种情况下,继承不是一个解决方案,因为我们不知道我们想在一个类中使用多少函数(类C有两个函数)。但是我们知道它们都有相同的原型不同类的成员函数具有不同的类型。因此,为了拥有任何同质容器(如std::vector
或std::array
),您需要将它们包装在一些可以代表它们的值类型中(如boost::variant
或boost::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
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法