将模板化对象存储在向量中(在单个向量中存储Class int,Class double) [英] Storing templated objects in a vector (Storing Class<int>, Class<double> in a single vector)

查看:94
本文介绍了将模板化对象存储在向量中(在单个向量中存储Class int,Class double)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个模板化的类,让它成为

There is a templated class, let it be

template<typename T> class A { std::vector<T> data; };

我在这里面临的问题是,用户可以创建此类的几种类型,但是我需要对其进行跟踪,最好的情况是我在另一个向量中引用了这些对象,但是由于所有类型都是不同的. 您能推荐一个可以将其封装的良好设计模式吗?

The problem I am facing here is, users can create several types of this class, but I need to track them, best case is I have a reference of these objects in another vector, but that would not work since all types are different. Can you recommend a good design pattern which can encapsulate this.

我可以存储指针,然后进行类型转换,但它并不优雅.

I can store pointers and then typecast it, but its not elegant.

如果提供的解决方案足够好,我也可以更改体系结构. 我要解决的基本问题是,我有一类自定义类型的向量,如何存储它们.

I can change the architecture as well, if the solution provided is good enough. The basic question I am trying to solve is, I have a class of vector of custom types, how do I store them.

推荐答案

如先前的评论所述-您首先需要确保这是您所需要的.

As previous comments stated - you first need to make sure this is what you need.

话虽如此,我在我的一个项目中也有类似的要求,最终我通过继承和PIMPL解决了该问题,如下所示:

With that been said, I had a similar requirement in a project of mine, which I eventually solved with inheritance and PIMPL, as follows:

class A{
private:
    struct Abstract {
        virtual void f() = 0;
    };

    template <typename T>
    struct Implementation : public Abstract {
        std::vector<T> data;
        virtual void f() {...}
    };

    std::unique_ptr<Abstract> impl;

public:
    template <typename T>
    A(): impl(std::make_unique<Implementation<T> >()){}

    void f() {impl->f();}
};

这使您可以创建类型为"A"的对象的容器,并通过其中定义的公共接口(方法"f")对其进行访问.每个"A"对象的基础类型"T"在构造时指定.所有其他特定于类型"T"的实现细节都被隐藏了.

This allows you to create a container of objects of type 'A', and access them via the public interface defined therein (the method 'f'). The underlying type 'T' of each 'A' object is specified on construction. All other implementation details specific to the type 'T' are hidden.

该解决方案承受了虚拟功能的固有开销.我不确定它与std :: any方法在性能方面的比较.

The solution suffers the inherent overhead of virtual functions. I'm not sure how it compares to the std::any approach performance-wise.

这篇关于将模板化对象存储在向量中(在单个向量中存储Class int,Class double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆