Template polymorphism

I'm making a class which will provide a common interface to two very different implementations. What do you think is the best design pattern to use to achieve this? What do you think about template polymorphism?

I'm currently looking into template polymorphism because I want to avoid the runtime overhead of normal polymorphism. It's also important that I simplify the usage of the class which I think I've achieved when you look at int main() below.

The implementation is obviously more complicated with templates, but that's not really an issue and I think the benefits of finding errors during compile-time versus runtime is worth it but I'm interested in what you have to say.

Here's a side-by-side comparison of the methods. If I have a terrible implementation, please feel free to say so.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//template polymorphism
#include <iostream>

struct Impl // Virtual base
{
  virtual void print() = 0;
};

struct Impl1 : Impl
{ 
  void print() { std::cout << "impl1\n"; }
};

struct Impl2 : Impl
{
  void print() { std::cout << "impl2\n"; }
};

enum IMPL1{};
enum IMPL2{};

template <class T> class Wrapper {};

template <> class Wrapper<IMPL1>
{
  Impl1 impl;
public:
  void print() { impl.print(); }
};      

template<> class Wrapper<IMPL2>
{
  Impl2 impl;
public:
  void print() { impl.print(); }
};      

int main()
{
  Wrapper<IMPL1> impl1;
  impl1.print();

  Wrapper<IMPL2> impl2;
  impl2.print();
  return 0;
}
// Normal polymorphism
#include <iostream>

struct Wrapper // Wrapper
{
  virtual void print() = 0;
};

struct Impl1 : Wrapper
{ 
  void print() { std::cout << "impl1\n"; }
};

struct Impl2 : Wrapper
{
  void print() { std::cout << "impl2\n"; }
};




















int main()
{
  Wrapper* impl1 = new Impl1;
  impl1->print();

  Wrapper* impl2 = new Impl2;
  impl2->print();
  return 0;
}
Last edited on
The left side could be rewritten like this without any breakage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct Impl1
{ 
  void print() { std::cout << "impl1\n"; }
};

struct Impl2
{
  void print() { std::cout << "impl2\n"; }
};

template <class T> class Wrapper
{
  T impl;
public:
  void print() { impl.print(); }
};
Topic archived. No new replies allowed.