Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain C++ templates to junior developers?

Tags:

c++

templates

One could break the question into two: how to read and to write templated code.

It is very easy to say, "it you want an array of doubles, write std::vector<double>", but it won't teach them how the templates work.

like image 502
Andrew T Avatar asked Dec 01 '22 11:12

Andrew T


1 Answers

I'd probably try to demonstrate the power of templates, by demonstrating the annoyance of not using them.

A good demonstration would be to write something simple like a stack of doubles (hand-written, not STL), with methods push, pop, and foldTopTwo, which pops off and adds together the top two values in the stack, and pushes the new value back on.

Then tell them to do the same for ints (or whatever, just some different numeric type).

Then show them how, by writing this stack as a template, you can significantly reduce the number of lines of code, and all of that horrible duplication.

like image 87
Paul Butcher Avatar answered Dec 04 '22 13:12

Paul Butcher