class A
{
public:
int x;
//create a vector of functors in B and C here
};
class B
{
public:
struct bFunctor
{
void operator()() const
{
//some code
}
};
};
class C
{
public:
struct cFunctor
{
void operator()() const
{
//some code
}
};
};
void main()
{
A obj;
//iterate through the vector in A and call the functors in B and C
}
我的问题是,在vector
和A
调用functors
时,B
课程C
的格式应该是什么?或者,只有这样才能在functor
中设置基数A
,并使functors
和B
中的C
从中获得?或者有更好的方法吗?
答案 0 :(得分:6)
基本上有两种方法(我可以想到ATM):
注意:在这两种情况下,我都会将cFunctor
和bFunctor
重命名为Functor
。它们嵌套在各自的类中,因此这种前缀没有多大意义。
类型擦除的示例是std::function
。
class A {
public:
int x;
std::vector<std::function<void(void)>> functors;
A() : functors { B::bFunctor(), C::cFunctor() }
{ }
};
如果您需要仿函数具有更高级的行为,Boost.TypeErasure
any
可能会有所帮助。
B::bFunctor
和C::cFunctor
继承。vector
。struct AbstractFunctor {
virtual void operator()() const = 0;
};
class B {
public:
struct Functor : public AbstractFunctor {
void operator()() const {
//some code
}
};
};
class A {
public:
int x;
std::vector<std::unique_ptr<AbstractFunctor>> functors;
A() {
// this could most probably be shortened with make_unique
functors.emplace_back(std::unique_ptr<AbstractFunctor>(new B::Functor()));
functors.emplace_back(std::unique_ptr<AbstractFunctor>(new C::Functor()));
}
};