1

Is there any benefit of templates over class hierarchy other than simplified generic algorithms? For example, is it more efficient to use a template over a class hierarchy? Templates are highly praised by programmers for financial tools, but I don't really understand why.

Plamen
  • 650
  • 1
  • 8
  • 27
  • Hm, can you give an example of where you’re unsure what to use? Generally templates and derived classes are quite different things although they have a large overlap. – Konrad Rudolph Jul 21 '13 at 12:50
  • 1
    I do not really understand what you want to compare. How would you substitute a class hierarchy with a (single) template class? Template classes and class hierarchies are completely different tools that are used to achieve different goals. – Alexander Weinert Jul 21 '13 at 12:52
  • At the minute not really... It's a question I was curious about. I don't really use templates much, even though I have some algorithms that I build using abstraction: the abstract base classes are fixed, so it feels that using a template in this setting is wrong. I have heard that templates manipulate memory management better, so I am considering rewriting my code with templates. For an example of application, people in Monte Carlo simulation have often told me they like to use templates but I don't exactly know where or why. – Plamen Jul 21 '13 at 13:37
  • Possible duplicate of [c++ standard practice: virtual interface classes vs. templates](https://stackoverflow.com/questions/1165963/c-standard-practice-virtual-interface-classes-vs-templates) – Trevor Boyd Smith Jun 15 '18 at 13:05

2 Answers2

5

we use templates instead of run-time dynamic polymorphism when speed is requirement and template might offer compile-time polymorphism (resolved at compile-time) without virtual methods lookup overhead.

From wikipedia:

Polymorphism is a common standard programming facility where derived objects can be used as instances of their base object but where the derived objects' methods will be invoked, where all invocations of virtual methods will be those of the most-derived class. This dynamically polymorphic behaviour is (typically) obtained by the creation of virtual look-up tables for classes with virtual methods, tables that are traversed at run time to identify the method to be invoked. Thus, run-time polymorphism necessarily entails execution overhead (though on modern architectures the overhead is negligible). However, in many cases the polymorphic behaviour needed is invariant and can be determined at compile time. Then the Curiously Recurring Template Pattern (CRTP) can be used to achieve static polymorphism, which is an imitation of polymorphism in programming code but which is resolved at compile time and thus does away with run-time virtual-table lookups.


Another example is templates ability to calculate at compile-time, for instance well known factorial as usual written like this

unsigned int factorial(unsigned int n) {
  return (n==0)? 1 : n * factorial(n-1); 
}

const int x = factorial(4); // == (4 * 3 * 2 * 1 * 1) == 24
const int y = factorial(0); // == 0! == 1 

is to be computed at run-time. But written with use of templates

template <int N>
struct Factorial {
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> {
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
const int x = Factorial<4>::value; // == 24
const int y = Factorial<0>::value; // == 1

is computed at compile-time, no run-time overhead is imposed.

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • If the overhead is negligible, why use it? I mean, it's easier to implement the class hierarchy. Or does it make a difference when you repeatedly (millions or billions of times) call a function that's called through a vtable? I am building a Monte Carlo algorithm where I use polymorphism at run-time, but I need to call the virtual functions a lot. Could this compromise performance? – Plamen Jul 21 '13 at 13:50
  • 1
    yes, of course it might, but you can just try it and eventually reimplement then using template, avoid pre-mature optimization. Moreover you might be interested in programming for [GPU (i.e. CUDA) - this is well suited for Monte Carlo purposes](http://docs.nvidia.com/cuda/cuda-samples/index.html#finance) – 4pie0 Jul 21 '13 at 14:37
  • OK, I will definitely run tests before implementing. CUDA is something that definitely interest me and will be a future project. – Plamen Jul 22 '13 at 13:00
5

templates vs class hierarchy

The main thing is the cost of the virtual function calls. If the computational cost of the actual wok of the function is small then the cost of virtual dispatch can be significant. This is especially the case compared to an inlined function and if used inside tight loops. Using runtime polymorphism rules out the possibility of functions being inlined.

C++ templates are a very powerful tool to have...

Along with the well known generic containers and algorithms like you find in the C++ standard library, C++ templates support a range of advanced techniques such as:

Essentially you are programming the compiler to build the classes you wanted. Used well this can give highly reusable optimal code. If misused it can give much more bloated object code than a more appropriate approach.

PeterSW
  • 4,921
  • 1
  • 24
  • 35