0

我有模板类“工厂”。工厂的原型如下:

template <class T>
class Factory
{
    public:
    Factory();
    ~Factory();

    //few more functions & data-members


    private:
    //few more functions & data-members
};

在 main() 中,我制作了多种类型的工厂,如下所示 -

int main()
{
    typedef Factory<int> IntFactory ;
    IntFactory A = IntFactory();

    typedef Factory<float> FloatFactory ;
    FloatFactory B = FloatFactory();

    //Complex is some user defined class
    typedef Factory<Complex> ComplexFactory ;
    ComplexFactory C = ComplexFactory();

    //Point3D is a user defined class
    typedef Factory<Point3D> Point3DFactory ;
    Point3DFactory D = Point3DFactory();

    //I may have several such initializations.

}

问题是如何创建对象数组 A、B、C、D 以防我想遍历它们?

4

3 回答 3

1

我认为你能做的最好的事情(在我的脑海中并且没有经过测试)是:

class FactoryBase
{
    public:
        virtual ~FactoryBase() = 0;
};

template <class T>
class Factory : public FactoryBase
{
    //...
};

int main()
{
    std::vector<FactoryBase*> factories;
    factories.push_back(new Factory<int>);
    factories.push_back(new Factory<Complex>);
    //... Make sure you delete these. Better yet, use a smart pointer.
    return 0;
}

注意一个vector指针,所有这些push_back(new ...)东西都非常容易受到异常和泄漏的影响......

于 2012-09-28T13:52:42.380 回答
1

(如果您不想使用基类方法,另一种选择)

typedef boost::variant<IntFactory, FloatFactory, ...>  FactoryType;

std::vector<FactoryType> vFactories;

然后使用访问者执行和方法...

链接变体的文档。

于 2012-09-28T13:55:34.457 回答
0

有很多方法可以做你想做的事......每一种都有优点和缺点......如果你在编译期间知道所有实例,这种方法可以正常工作:

包括

#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/container/vector.hpp>

函子

struct do_whatever
{
    template<typename T>
    void operator()(T& t) const
    {
        ...
    }
};

向量上的实例化和迭代

boost::fusion::vector<IntFactory, FloatFactory, ComplexFactory, Point3DFactory> vv(A, B, C, D);
boost::fusion::for_each(vv, do_whatever());
于 2012-09-28T16:18:55.033 回答