C++ templates, are they worth it?

Started by
10 comments, last by Ravyne 10 years, 3 months ago
Hi,
Just out of curiosity. I'm "just" a fanatic hobbyist and up till now developed my own 3d engine. With from a hobby point of view enough flexibility and fun stuff. Up till now it's nicely OOP designed, 80/20 data driven and "const correct" (structure is a gift :))

Now I was wondering, would it be interesting/ pay off to learn c++ templates:
- what will it bring?
- does my code get better readable or memory efficient?
- and what more?

I recently swapped most of my dynamic memory allocations by using vectors (except where it doesn't bring anything).

Who can convince me?

Ps: I'm not planning using templates yet because I dont need them at the moment for what I'm trying to achieve

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Advertisement

If you find yourself writing the same exact code over and over for different data types, learn templates and use them. If you don't find yourself doing that, it's fine to ignore templates for now.

Templates, like nearly all language features, can be used for good and for evil. Using templates just to use them is probably not a good idea. But when you need them, they can greatly simplify your life. You have to re-write less mostly-identical code, which leaves less room for stupid mistakes.

Basically, a template lets you write a function or a class with unknown types (and some unknown numbers), which nevertheless work correctly (and type-safe) for whatever type you supply. That doesn't sound like a big advantage at first, but it really is.

Template specializations further let you write classes or functions that even behave differently for different types, and going a bit more extreme (template metaprogramming), let you evaluate some quite non-trivial things at compile-time. Often, template metaprogramming isn't really necessary, but the code is a lot more elegant and more comprehensible (and has zero runtime cost).

Sometimes, templates are criticised for causing "bloat" but if you're being honest, you would have the same bloat if you wrote the identical functionality by hand. Except now you don't need to write it, and the compiler only instantiates what functions you call.

I recently swapped most of my dynamic memory allocations by using vectors

std::vector is a very good example of a template. It is much more comprehensive to think in terms of "access element at index 17 in a vector of foo objects" than to malloc some "raw memory" and do some pointer manipulations and typecasts to the same net effect, even if it might be slightly faster (in practice you can rely that it won't be any faster, the standard library is very mature and well-optimized, you have to try very hard and be a very good programmer to beat it).

The point about templates in this case is that vector does not need to worry what objects you will use it with (well, almost, there are some requirements), it will just work with one or the other type, and it will work in the exact same way, always.

Thanks, I didn't think about it that way using vectors. Where I'm basically using some of the benefits of templates. When I find myself writing functions over and over for several types, I'll get into it.

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

These are some pretty good starting points ("old-code-can-call-new-code" is a pretty succinct description):
http://isocpp.org/wiki/faq/templates
http://isocpp.org/wiki/faq/big-picture#generic-paradigm
http://isocpp.org/wiki/faq/big-picture#multiparadigm-programming
http://isocpp.org/wiki/faq/big-picture#old-code-can-call-new-code
http://isocpp.org/wiki/faq/cpp11-language-templates

One other thing -- they go hand in hand with "auto" and genericity:
http://isocpp.org/wiki/faq/cpp11-language#auto

For instance, instead of writing:


int add(int a, int b) { return a + b; }
float add(float a, float b) { return a + b; }
double add(double a, double b) { return a + b; }

int x = add(1, 2);
float y = add(1.f, 2.f);
double z = add(1., 2.);

You can simply write:


template <typename T>
T add(T a, T b) { return a + b; }

auto x = add(1, 2);
auto y = add(1.f, 2.f);
auto z = add(1., 2.);

So they help you achieve generic, reusable code that doesn't just work for a particular type, but for a bunch of types that happen to satisfy a concept: http://en.cppreference.com/w/cpp/concept

// This concept is implicit here -- operator "+" has to exist. You can make it explicit with type-traits, static_assert, and enable_if.

This is useful -- say, instead of "add" taking two numbers, think of "will_first_monster_win" taking two monsters:


template <typename FirstMonsterType, typename SecondMonsterType>
bool will_first_monster_win(const FirstMonsterType & first_monster, const SecondMonsterType & second_monster)
{
  return strength(first_monster) >= strength(second_monster); // super-fancy combat algorithm!
}

Now, if you add new monster types to your game, your "will_first_monster_win" function will keep working unmodified -- as long as the relevant (new) "strength" function exists (let's call this particular existence requirement a "has-strength" concept -- in other words, FirstMonsterType & SecondMonsterType in the "will_first_monster_win" function will successfully match any types that satisfy the "has-strength" concept). In other words, you can extend your code (and add new code) without modifying the already written ("old") code: https://en.wikipedia.org/wiki/Open/closed_principle

// Note: the linked article happens to use inheritance/inclusion-run-time-polymorphism (typical OOP technique) to illustrate this; in many ways, however, templates/compile-time-polymorphism (typical Generic Programming) as in the "will_first_monster_win" example will work just as well if not better.

Without templates, you'd have to know the types of your monsters in advance / right at the moment when you're implementing "will_first_monster_win" -- and then rewrite it / provide overloads / etc. each time you add new monster type. Or just settle for a boring game with fixed monster types :-(

With templates you can save quite some time, speed up your experiments, and keep adding increasingly cruel monsters, so you can provide more fun for the players :-)


Without templates, you'd have to know the types of your monsters in advance / right at the moment when you're implementing "will_first_monster_win" -- and then rewrite it / provide overloads / etc. each time you add new monster type. Or just settle for a boring game with fixed monster types :-(

Well I'd argue that it would be rare to have code that call these functions with explicitly those monster types :-). More likely you'd use runtime polymorphism here (e.g. a Monster base class that has a strength property), since the calling code would most likely/hopefully be ignorant of the specific monster type.

But, your general point of possibly replacing runtime polymorphism with compile-time polymorphism stands. Templates can offer an alternative to virtual function calls (speeding things up since an indirection through a vtable isn't needed).

http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism

std::swap is another good example of how templates help to write code that is both generic and reusable, and expressive, but still safe.

Swapping two objects has three major requirements. You want the elements swapped (duh!) and it should generally work for every type (or nearly every type), but it should only allow being done in a meaningful way. And of course, it should be as fast as possible, optimized for individual types.

A simple template like template<class T> void swap(T& a, T& b) as supplied by the standard library provides all of that. It accepts any kind of type T, but it enforces that whatever T is, a and b are still necessarily the same type (which makes sense: for example, if you were to swap an integer and a string, none could hold the other's value in a meaningful way). There is a default implementation which will use the object type's assignment operator, but for types where a specialized version would be more efficient, a template specialization is supplied that works in "some other" way.

The compiler will use the specialization (if present) and fall back to the default otherwise, and you don't even know. You don't want to know either, because you don't want to care. What you care about is expressing "I want to swap these two", and that is what's happening.

The quite well known array_size template (template<typename T, size_t N> constexpr size_t array_size(const T(&)[N]){ return N; }) is a simple example of how templates can be useful to encode variable/tweakable compiletime information in a meaningful and safe way. It's a pretty cool hack, too.

Of course #define NUM_ELEMENTS 20 or even using the literal 20 (assuming that is a particular array's size) will work just the same, but it is not nearly as expressive or universal, and woe if you change the size in one place and forget doing it in another!

Referring to the array's size via the array_size template not only explains to someone reading your code what your desired intent is, but it is also safe in presence of change (since if you change your array size to e.g. 15, the compiler will instantiate a different function that returns a different constant value, namely 15). Again, you don't even know that this is happening, but your program is correct.

Now imagine you write an utility function that accepts some array with some known size defined in some other module that's maintained by someone else. What was the name of that #define again? Let's hope you there are not several ones with ambiguous names and different values! Using the above template, you couldn't care less, you're letting the compiler figure out how large the array is.

You should not stop learning C++. Go for templates:

  • Templates allow generic programming
  • Templates are the base for many useful C++ idioms (an example of list)
  • Templates allow generic meta-programming
  • Templates are type-safe
  • Templates allow static code inspection (see SFINAE)
  • Templates represent a powerful concept that helps fighting DRY violations and refactor code
  • Templates are evaluated by the compiler not at run-time
  • The use of templates is fun and can lead you to many interesting code design problematic
  • Many high quality code architectures use templates (C++ standard library for instance)
  • ...
In the places where you didn't replace raw allocation with vectors because you felt there was no gain, are you sure that code is exception safe?

Templates have nightmarishly awful syntax and can be used to produced wholly illegible code almost instantaneously with little to no effort. On the other hand, once you have the stuff written (if you did it sanely) then the places where you make use of it are clear and efficient. Just learn how they work and fiddle with it for a while. They're not that complicated, but people use them to make horrific, awful things that work very well. For example, vector is a template class, and you can see how useful it is. If you look at the code that implements it you may vomit, but making use of it feels natural and effective.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement