C++ 如何创建函子的 std::vector

c++ how to create a std::vector of functors

本文关键字:std vector 何创建 创建 C++      更新时间:2023-10-16
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
}

我的问题是,在BC中,A在课堂中呼叫functorsvector应该采用什么格式?还是唯一的方法是在A中有一个基础functor,并在Bfunctors并从中C派生?还是有更好的方法?

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

注意:在这两种情况下,我都会将cFunctorbFunctor重命名为简单地Functor。它们嵌套在各自的类中,因此这样的前缀没有意义。

文字已擦除

类型擦除的示例std::function

class A {
public:
    int x;
    std::vector<std::function<void(void)>> functors;
    
    A() : functors { B::bFunctor(), C::cFunctor() }
    { }
};

如果您需要函子具有更高级的行为,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()));
    }
};