【问题标题】:Can abstract class interface be templated抽象类接口可以模板化吗
【发布时间】:2019-08-01 22:50:43
【问题描述】:

抽象类接口可以模板化吗 我们可以在派生类中使用模板来填充参数吗? 如何为这些类型的需求定义接口参数

  class iconfigurator
    {
    public:
        iconfigurator();
        virtual ~iconfigurator();
        //EXpect the std::vector<class entry>& entries to be Template type.              
        virtual bool config(const std::string& configName,std::vector<class entry>& entries) const = 0;    
    };

    class derivedconfigurator : public iconfigurator
    {        
    public:
        derivedconfigurator();
        virtual ~derivedconfigurator();    
        virtual bool config(const std::string& configName,std::vector<class another_entry_type>& entries) const = 0;    
    }

    class derivedconfigurator2 : public iconfigurator
    {    
    public:
        derivedconfigurator2();
        virtual ~derivedconfigurator2();    
        virtual bool config(const std::string& configName,std::maps<key, value>& entries) const = 0;
    }

【问题讨论】:

  • 您的示例中的 Types 是什么?
  • 你想在这个类的什么地方使用模板参数?目前尚不清楚您要达到的目标。
  • 我已经编辑了代码。
  • 如果你问是否可以做template &lt;typename Types&gt; class iconfigurator {...};,那么可以——但要注意iconfigurator&lt;SomeType&gt;iconfigurator&lt;SomeOtherType&gt; 是截然不同的不相关的类;例如,您将无法拥有std::vector&lt;iconfigurator*&gt; 并以统一和多态的方式对待它们。如果你问你是否可以做template &lt;typename Types&gt; virtual bool config(...); 那么不,你不能。没有虚函数模板之类的东西。
  • @IgorTandetnik 听起来像是一个答案!

标签: c++ templates c++14


【解决方案1】:

模板只是编写 N 个函数或类的捷径。

template <typename T> class MyClass {}
MyClass<int> mc1 {};
MyClass<int> mc2 {};

编译器将为 2 个不同的类生成代码:MyClass&lt;int&gt;MyClass&lt;double&gt;。您可以自己编写它们,它会完全一样!因此,normal 类和从模板生成的类之间实际上没有区别。所以,对于抽象类接口能否被模板化这个问题,答案是肯定的。请注意,每种类型都有 1 个抽象接口,如上所述(就像您编写了 MyClass 的两个定义一样)。当然,您也可以在派生类中使用模板。

你不能做的是使用模板化的虚函数。为什么?模板在编译时生成代码。虚函数是关于确定在运行时调用哪个函数。因此,编译器不可能知道要生成哪些代码,因为要调用的函数是在运行时确定的。

模板化抽象接口示例:

template <typename T>
struct Base
{
    virtual ~Base() = default;

    // YOU CAN DO THIS
    virtual void test() const = 0;

    // BUT YOU CANNOT DO THIS
    /*template <typename D>
    virtual void fct();*/ 

};

template <typename T>
struct Derived : Base<T>
{
    void test() const override {}
};

int main()
{
    Base<int>* b = new Derived<int>();
    b->test();
    delete b;
    return 0;
}

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多