c ++如何创建一个函子的std :: vector

sn7*_*710 3 c++

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)

我的问题是什么应该是格式vectorA调用functorsBC?或者是,这是有可能有一个基础的唯一途径functorA,使functorsBC从中获得?还是有更好的方法?

Bar*_*icz 6

基本上有两种方法可以解决这个问题(我可以想到ATM):

注意:我会重命名cFunctorbFunctor简单地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可能会有所帮助.

多态

  1. 创建一个抽象的仿函数类型.
  2. 制作B::bFunctorC::cFunctor继承它.
  3. 存储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)