如何创建共享方法的派生类容器? (C++)

问题描述 投票:0回答:0

我是 C++ 的新手,我正在尝试创建一个结构,它允许我创建一个函数列表,我可以为该列表的每个成员使用相同的函数 (

.create()
)。这基本上可以让我在一个选项卡中拥有所有小部件的注册表。

最终目标是将我的

Tab
对象也放在一个类似的列表中。

我的代码(下方)在 VS 中给出了这些错误:

Error (active)  E0289   no instance of constructor "std::list<_Ty, _Alloc>::list [with _Ty=std::shared_ptr<Program::Widget>, _Alloc=std::allocator<std::shared_ptr<Program::Widget>>]" matches the argument list    Tabs.cpp    line 12 

Error (active)  E0289   no instance of constructor "Program::WidgetA<T>::WidgetA [with T=Program::Widget]" matches the argument list    Tabs.cpp    line 13 

Error (active)  E0289   no instance of constructor "Program::WidgetB<T>::WidgetB [with T=Program::Widget]" matches the argument list    Tabs.cpp    line 14 

// Tabs.cpp
#include "Tabs.h"

#include <string>

namespace Program
{
    Tab::Tab(std::string t_id) { id = t_id; }

    TabA::TabA(std::string t_id) : Tab::Tab(t_id)
    {
        std::string id_name = "A" + id;
        WidgetList widgets = {
            WidgetA<Widget>(id_name),
            WidgetB<Widget>(id_name)
        };
    }
    void TabA::generate()
    {
        // Loop that does .create() on all the objects in widgets
    }
}
// Tabs.h
#pragma once

#include <string>

namespace Program
{
#ifndef TABS_H
#define TABS_H

    class Tab
    {
    public:
        Tab(std::string t_id);
        Tab() = default;
        std::string id;
        WidgetList widgets;
    };

    class TabA : public Tab
    {
    public:
        TabA(std::string t_id);
        TabA() = default;
        void generate();
    };

#endif !TABS_H
}
// Widgets.cpp
#include "Widgets.h"

#include <string>

namespace Program
{
    void WidgetA<Widget>::create()
    {
        // Code to launch widget
    }

    void WidgetB<Widget>::create()
    {
        // Code to launch widget
    }
}
// Widgets.h
#pragma once

#include <string>
#include <list>

namespace Program
{
#ifndef WIDGETS_H
#define WIDGETS_H

    class Widget
    {
    public:
        Widget(const std::string& w_id) : id(w_id) {}
        virtual ~Widget() {}
        virtual void create() = 0;
        std::string id;
    };

    template< typename T >
    class WidgetA : public Widget
    {
    public:
        WidgetA(const std::string& w_id, const T& data) : Widget(w_id), m_data(data);
        void create();
    private:
        T m_data;
    };

    template< typename T >
    class WidgetB : public Widget
    {
    public:
        WidgetB(const std::string& w_id, const T& data) : Widget(w_id), m_data(data);
        void create();
    private:
        T m_data;
    };

    typedef std::list< std::shared_ptr<Widget> > WidgetList;

#endif !WIDGETS_H
}

我当前的代码来自this question,尽管它提供的几个例子让我不确定它究竟是如何使用/预期的。

c++ data-structures c++17 abstract-class paradigms
© www.soinside.com 2019 - 2024. All rights reserved.