• Advertisement
Sign in to follow this  

C++ templates, are they worth it?

This topic is 1469 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites


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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites


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. 

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement