【问题标题】:How to implement an abstract method when abstract class is used in a variadic context在可变参数上下文中使用抽象类时如何实现抽象方法
【发布时间】:2017-02-17 16:39:45
【问题描述】:

如何在下面的代码中实现通用情况下的抽象基类。代码是从我正在研究的库中简化的。因此,int 和 double 的显式实现不是一种选择。

template <typename T>
struct Foo
{
  virtual void send(T t) = 0;
};

template <typename...T>
struct Bar : Foo<T>...
{
  void send(T t) override { // does not compile because 
                            // abstract method not implemented
  }
};

int main() {
  // example usage
  Bar<int, double> b;

  b.send(1);
  b.send(2.3);
}

非常感谢。

编辑:将虚拟添加到抽象方法。

【问题讨论】:

    标签: c++ templates c++11 variadic-templates pure-virtual


    【解决方案1】:

    下面的例子呢?

    首先,我认为你需要在Foo 中定义virtual send() 方法(如果你想要它是纯虚拟的)。

    接下来,您可以声明一个中间模板类 (Foo2),其中实现 override send()

    最后,您可以在Bar 中使用模板send() 方法来选择正确的虚拟send() 方法。

    #include <iostream>
    
    template <typename T>
    struct Foo
     { virtual void send(T t) = 0; };
    
    template <typename T>
    struct Foo2 : Foo<T>
     {
       void  send(T) override
        { std::cout << "sizeof[" << sizeof(T) << "] " << std::endl; }
     };
    
    template <typename...T>
    struct Bar : Foo2<T>...
     {
       template <typename U>
       void send (U u)
        { Foo2<U>::send(u); }
     };
    
    int main()
     {
       Bar<int, double> b;
    
       b.send(1);    // print sizeof[4]
       b.send(2.3);  // print sizeof[8]
     }
    

    【讨论】:

    • 嘿,你能告诉我Foo2&lt;T&gt;...Foo2&lt;T...&gt;之间的区别吗(括号外的点与括号内的点)
    • @Brandon - 是完全不同的东西;如果你写Foo2&lt;T...&gt;,你声明一个基类Foo2&lt;T0, T1, T2 /* etc*/&gt;,带有sizeof...(T)模板参数;如果你写Foo2&lt;T&gt;...,你声明sizeof...(T)基类Foo2&lt;T0&gt;, Foo2&lt;T1&gt;, Foo2&lt;T2&gt; /* etc */,每个都有一个模板参数
    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2016-11-08
    • 1970-01-01
    • 2012-09-21
    相关资源
    最近更新 更多