Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 594
Felix Petriconi Avatar asked Oct 08 '16 23:10

Felix Petriconi


People also ask

Can an abstract class define both abstract methods and non abstract methods?

Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user. An abstract class having both abstract methods and non-abstract methods.

Do you have to implement all methods of an abstract class?

The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class. All the methods in an interface are implicitly abstract unless the interface methods are static or default.

Is it compulsion for abstract class to have abstract method?

And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it.

How do you implement an abstract method in Java?

An abstract method doesn't have any implementation (method body). A class containing abstract methods should also be abstract. We cannot create objects of an abstract class. To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass.


1 Answers

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]
 }
like image 53
max66 Avatar answered Oct 20 '22 17:10

max66