Type erasure with templated method

1.4k views Asked by At

I have a number of classes which take an object of unspecified type and return a result with a fixed type. Additionally these objects are templated which changes the computation of the results. I would like to hide these objects behind a common interface. The example below should make it clear. struct Work is the interface and there exist multiple classes like struct WorkImpl. Additionally there are multiple types like struct A and struct B which interact. In my case they are templated as well and must not be polymorphic. The problem is how to "forward" the work call to the WorkImpl object?

#include <iostream>

struct Result
{

};

struct Work
{
  virtual ~Work() { }

  template <typename U>
//  virtual Result work(const U& u) = 0;  // this is not possible, of course!
  Result work(const U& u) { std::cout << "Work" << std::endl; }
};

struct B
{

};

struct A
{
  A& operator =(const B& b) { return *this; }
  Result result() { return Result(); }
};

template <typename T>
struct WorkImpl : public Work
{
  template <typename U>
  Result work(const U& u)
  {
    std::cout << "WorkImpl" << std::endl;
    T t;
    t = u;
    return t.result();
  }
};

int main()
{
  Work* w = new WorkImpl<A>();
  w->work(B());
  return 0;
}
1

There are 1 answers

5
sehe On

I don't really see what the question is.

The code compiles.

You don't want to polymorphism but

  • you forget that static polymorphism is also polymorphism
  • you gratuitously use inheritance, despite the fact that there is no common interface at all

I'd suggest to just get the parameter out of the interface. The simplest way to type-erase that would be to use std::function<Result()> and be done.

I can add a small sample if required.