How to implement an abstract method when abstract class is used in a variadic context
Asked Answered
N

1

11

How to implement in the following code the abstract base class in a generic case. The code is simplified from a library I am working on. So an explicit implementation for int and double is not an option.

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);
}

Many thanks in advance.

Edit: Added virtual to abstract method.

Nicodemus answered 8/10, 2016 at 23:2 Comment(0)
K
6

What about the following example?

First of all, I think you need define virtual the send() method in Foo (if you want it pure virtual).

Next, you can declare a intermediate template class (Foo2) where implement the override send()

Last, you can use a template send() method in Bar to select the correct virtual send() method.

#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]
 }
Keener answered 8/10, 2016 at 23:48 Comment(2)
Hey, can you tell me what the difference is between: Foo2<T>... and Foo2<T...> (dots outside bracket vs. inside bracket)Attention
@Attention - are completely different things; if you write Foo2<T...>, you declare a single base class, Foo2<T0, T1, T2 /* etc*/>, with sizeof...(T) template parameters; if you write Foo2<T>..., you declare sizeof...(T) base classes, Foo2<T0>, Foo2<T1>, Foo2<T2> /* etc */, with a single template parameter eachKeener

© 2022 - 2024 — McMap. All rights reserved.