Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!

1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!

C++ templates, are they worth it?

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
13 replies to this topic

#1 cozzie   Members   -  Reputation: 2761


Posted 08 January 2014 - 02:19 PM

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


#2 richardurich   Members   -  Reputation: 1187


Posted 08 January 2014 - 02:53 PM

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.

#3 samoth   Crossbones+   -  Reputation: 5648


Posted 08 January 2014 - 03:10 PM

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.

Edited by samoth, 08 January 2014 - 03:19 PM.

#4 cozzie   Members   -  Reputation: 2761


Posted 08 January 2014 - 03:36 PM

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.

#5 Matt-D   Crossbones+   -  Reputation: 1548


Posted 08 January 2014 - 04:40 PM

These are some pretty good starting points ("old-code-can-call-new-code" is a pretty succinct description):

One other thing -- they go hand in hand with "auto" and genericity:

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 :-)

Edited by Matt-D, 08 January 2014 - 04:48 PM.

#6 phil_t   Crossbones+   -  Reputation: 5288


Posted 08 January 2014 - 05:48 PM

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).


#7 samoth   Crossbones+   -  Reputation: 5648


Posted 09 January 2014 - 08:20 AM

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.

#8 a.lasram   Members   -  Reputation: 187


Posted 09 January 2014 - 06:04 PM

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)
  • ...

#9 Aardvajk   Crossbones+   -  Reputation: 8365


Posted 10 January 2014 - 07:41 AM

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?

#10 Khatharr   Crossbones+   -  Reputation: 3694


Posted 10 January 2014 - 07:36 PM

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.

#11 Gasimzada   Members   -  Reputation: 206


Posted 11 January 2014 - 07:19 AM

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


What do you mean by "Except where it doesn't bring anything"? Why would you use C array in a C++ code? With zero optimizations, I don't believe the performance would be so much different, as std::vector is just a wrapper around C style array? However the functionality you get with STD arrays is totally worth performance. 


And to answer your question about templates, of course learn it. Templates can be scary (it was for me); however once you get comfortable with it, you can write codes that are very flexible. 

#12 iMalc   Crossbones+   -  Reputation: 2397


Posted 11 January 2014 - 04:08 PM

First learn to make good use of templates indirectly, e.g. as someone mentioned, through using vector, map, pair etc. Then once you're very comfortable with that, you might want to start getting involved with them directly i.e. seeing how they are written and then writing your own.

The same advice I give for learning OOP and classes fwiw.

"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

#13 spacerat   Members   -  Reputation: 762


Posted 11 January 2014 - 05:40 PM

well, templates can partially be replaced by the new "auto" type in c++

#14 Ravyne   GDNet+   -  Reputation: 10405


Posted 11 January 2014 - 09:39 PM

well, templates can partially be replaced by the new "auto" type in c++


No, I don't think so. Not in C++11 anyways. The use of the 'auto' keyword can make it so that you don't have to state an explicit template type more than once when once will do, but since auto is not a type itself -- it only infers the type of an expression known to the compiler -- it needs a type on which to act on in the first place, template or otherwise.


In C++14 I believe they've allowed for auto parameters in lambdas for sure (and I think other functions too), and for return types -- and that can be used for something that's vaguely a subset of templates. But its AFAIK just shorthand for actual templates, you can't access variadic template parameters, can't specialize, and you can't even constrain types at all (maybe with traits-lite? I'm not sure). Its very, very limited.

throw table_exception("(ノ ゜Д゜)ノ ︵ ┻━┻");

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.