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
}
Run Code Online (Sandbox Code Playgroud)
我的问题是什么应该是格式vector类A调用functors中B和C?或者是,这是有可能有一个基础的唯一途径functor中A,使functors中B并C从中获得?还是有更好的方法?
基本上有两种方法可以解决这个问题(我可以想到ATM):
注意:我会重命名cFunctor并bFunctor简单地Functor在两种情况下.它们嵌套在各自的类中,因此这种前缀毫无意义.
类型擦除的例子是std::function.
class A {
public:
int x;
std::vector<std::function<void(void)>> functors;
A() : functors { B::bFunctor(), C::cFunctor() }
{ }
};
Run Code Online (Sandbox Code Playgroud)
如果您需要仿函数具有更高级的行为,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()));
}
};
Run Code Online (Sandbox Code Playgroud)