如何创建多个模板对象的数组

时间:2012-09-28 13:43:18

标签: c++ arrays templates

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

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的数组 迭代它们?

3 个答案:

答案 0 :(得分: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 ...)内容都非常容易受到异常和泄漏的影响......

答案 1 :(得分:1)

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

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

std::vector<FactoryType> vFactories;

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

关联variant的文档。

答案 2 :(得分: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());