如何创建模板化对象的数组/向量

How to create an array/vector of templated objects

本文关键字:数组 向量 对象 何创 建模      更新时间:2023-10-16

我有一个模板类,它是一个模板,作为MFC CWnd对象的包装器。

在主类中,我想有一个面板控件的集合,但我不明白如何创建它们的数组,因为它们显然派生自不同的基类(即 CButtonCtrl、CListBox 等)。

template<typename W>
class Component : public W
{
public:
    Component(uint_t nId = -1, CWnd *pParent = NULL, const char *pName = NULL)
        : mParent(pParent)
        , mName(pName)
        , mId(nId)
    {
        //std::cout << ((mName != NULL) ? mName : "NULL") << ": " << (void *)this << ": Id:" << mId << " Parent:" << (void *)mParent << std::endl;
    }
    const char *getName(void) const { return mName; }
    void setId(uint_t nId) { mId = nId; }
    uint_t getId(void) const { return mId; }
    void setParent(CWnd *pParent) { mParent = pParent; }
    CWnd *getParent() const { return mParent; }
private:
    uint_t mId;
    CWnd *mParent;
    const char *mName;
};

主类:

class Panel : public Component<CDialog>
{
public:
    Panel(uint_t nId = -1, CWnd *pParent = NULL, const char *pComponentName = NULL);
    virtual ~Panel(void) {};
    virtual void CreateWnd(CWnd *pParent = NULL);
    template <typename W>
    void addComponent(Component<W> *pComponent)
    {
    }
    template <typename W>
    void removeComponent(Component<W> *pComponent)
    {
    }
    void Show(bool bShow = true) override;
protected:
    typedef std::vector<Component<?> *> Components;
private:
    Components mComponents;
};
在 Java 中,像

这样的未知泛型有一个语法Component<?>所以我可以在数组中存储公共对象的集合,但我不知道如何在C++中做到这一点。我知道我必须使用指针,因为slcing,但这不是这里的问题。

使用 Visual Studio 2010。

您可能想尝试boost::anystd::any