Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I decided to improve my knowledge in template meta-programming. I know the syntax and rules and been playing with counteless examples from online resources.

I understand how powerful templates can be and how much compile time optimization they can provide but I still cant "think in templates", I can't seem to know by myself if a certain problem could be best solved with templates and if it can, how to adapt that problem to templates.

Is there some kind of online resource or book that teaches how to identify problems that could best be solved with templates and how to adapt that problem?

share|improve this question
5  
If all you have is a hammer, everything looks like a nail ;-) Don't try too much about thinking about using templates for all and everything, at least, not if you are not going to design the next version of the C++ standard library. –  Doc Brown Nov 28 '11 at 18:27
    
you're right, im not going to look at production code and try to fit TMP everywhere heh :p this is just for personal learning, because i know how powerful they can be and i love how some great C++ programmers (like STL who works on MS) can apply TMP so fast to a given problem and ir looks so awsome. STL has a few videos on channel9 that really got me impressed about TMP thats why i want to learn more. –  sap Nov 28 '11 at 21:54
add comment

9 Answers

Books:

Modern C++ design

C++ Template Metaprogramming

Being familiar with recursion and functional programming is a huge plus, as that's what a lot of tmp involves. It's turing complete and so essentially anything is possible, although usually it boils down to applying pure functions to constants or generating types from other types.

Warning: tmp is an ugly monster that turns nice code into spaghetti. The more you use it the less you will like C++. It is an evil thing.

share|improve this answer
    
thanks for the answer, im checking those books out! –  sap Nov 28 '11 at 21:40
1  
+1 for “tmp is an ugly monster”. C++ is good at some things, just like any language; but metaprogramming isn’t one of them. –  Jon Purdy Nov 28 '11 at 22:09
    
"Modern C++ design" is a classic, but IIRC more about implementing things using clever template tricks than about deciding what should be implemented as a template. The no. 1 principle for that is probably "don't" - the most common reasons for needing a template are already covered by the standard library (esp. C++11), Boost, and other already-existing libraries, so needing to roll your own isn't really an everyday thing. –  Steve314 Nov 29 '11 at 23:41
    
C++ Template Metaprogramming is just the user manual of a part of boost. Doesn't teach you much about choosing application for which it is pertinent nor about how to do similar things in C++. –  AProgrammer Dec 10 '11 at 15:26
add comment

Learn Haskell or some other pure functional language (Lisp, Scheme, OCaml to name a few, you can find more on Wikipedia).

Considering Haskell, you can find more information about it's metaprogramming facilities here.

Template programming follow much the same rules actually.

share|improve this answer
1  
Note that Haskell has its own templating system: Template Haskell. –  Matt Fenwick Nov 28 '11 at 18:32
2  
@MattFenwick: Yeah. And it's still Haskell, unlike c++ templates. :) –  Macke Nov 28 '11 at 18:34
    
i havent worked with a functional language since scheme at college. not that i dont like it, its just never had a chance on work and if i have to spend my free time coding or learning more i just rather learn something else (like TMP!) :) –  sap Nov 28 '11 at 21:50
    
@sap: Well, you need to get into the same mode of thinking... –  Macke Nov 28 '11 at 22:08
    
@sap: Actually, Scheme might be a great language to get used to compile-time metaprogramming. Its macro system is extremely capable and elegant while achieving a similar effect to C++'s templates (I think. I haven't used C++ too much though). –  Tikhon Jelvis Nov 30 '11 at 20:30
add comment

Just because you can do something with templates doesn't mean you should. Practically speaking unless when you are designing you think this is an awesome job for templates, its probably better to not use them. if you think too much in templates you just create insanely abstracted code that is just as bad as a single giant function.

share|improve this answer
    
thanks for the answer, yes i understand that, i just want to learn :) –  sap Nov 28 '11 at 21:47
    
I agree with the above. In the cases where I have used templates, it was usually a result of refactoring existing code. Once you are using your original code in new ways, the template appears more clearly as an improvement to the original. It is harder to tell if a template is useful when doing the design in advance of having known use cases. –  Sam Goldberg Nov 30 '11 at 15:23
add comment

Keep in mind that templates being the best solution is very rare. I've only defined my own once in the last 5 years, and my peers that reviewed that code had never done it. The cases where templates make a lot of sense have mostly already been implemented in standard libraries.

For generic programming, the thing to look out for is that you are copying and pasting functions to make only minor changes, like in constants or types, and can't figure out a clean way to use something like inheritance or function parameters to avoid repeating yourself.

One fairly common way templates are used is for type safety, if you have types that behave the same, but for whatever reason you don't want them accidentally mixed up.

For compile time calculation using templates, the thing to look out for is resource-intensive calculations where all its inputs are known at compile time, but where different constant inputs are used in different places throughout the code. However, keep in mind this will slow down your compiles every single time, so often it is preferable to just hard code the results manually, if they don't change very often.

Some advocates use templates for micro-optimizations like avoiding virtual table lookups using static polymorphism, or for loop unrolling, but in my opinion the complexity usually outweighs performance gains unless your code is very performance-critical.

share|improve this answer
    
thank you so much for the answer, ill keep those points in mind. i know that i cant use it for everything (like someone said before, i cant start seeing everything as a "nail") and if i understand correctly TMP excels in library developement (entire C++ does), im doing this just to learn and NOT to apply it in every production code that i create from now on. and wow only once in 5 years? i guess that shows how rare TMP can REALLY improve code. –  sap Nov 28 '11 at 21:46
add comment

Basically, there are several good reasons to use templates :

  1. You have a function or a class that has the same functionality for different types. Good example of good templates use is the boost library
  2. you want to use static polymorphism, and get compile errors, instead of run-time errors
  3. you want to get a specific behavior depending on some static parameters. For example, boost::type_traits provides very good examples.
share|improve this answer
    
thanks! ive used type traits before, really cool stuff! is enable_if also a type trait? or just a SFINAE "condition"? because i've used it before (on code review) and it seemed so powerfull but i fail to apply it to different problems. –  sap Nov 28 '11 at 21:49
    
@sap It is a type trait, which can be implemented using SFINAE. –  BЈовић Nov 29 '11 at 7:37
add comment

You should definitely look into templates in C++! This will greatly help you to understand topics like Design Patterns and Generic Programming. Do compare them with what other languages offer you. In precise you should use templates particularly in the following scenarios:

  1. Generalization & Code Reuse
  2. Flexibility
  3. Time & Budget Constraints
  4. Lack of expertise for a certain task

Here is a good online resource for you: http://en.wikipedia.org/wiki/Generic_programming#Templates_in_C.2B.2B

share|improve this answer
    
i know what they can be used for not just how to apply that knowledge to given problems, but still a nice read thanks :) –  sap Nov 28 '11 at 21:51
add comment

A simple indicator of when a template would improve your code, is when you see that your code is frequently requiring you to cast an object to a different type. An example I found in my own Java code, which triggered me to convert an existing method signature to a template:

    public MsgBase getLastSentMessage(Class<? extends MsgBase> msgBaseClass)

My client code always looked like this:

    OrderResponse response = (OrderResponse) getLastSentMessage(OrderResponse.class);

and whenever I used that method, I had to cast the result to the correct subclass of the MsgBase type. The improved method signature was:

    public <T extends MsgBase> T getLastSentMessage(Class<T> clazz)

Now the client code was:

     OrderResponse response = getLastSentMessage(OrderResponse.class);

So to summarize, if you find yourself doing a lot of casting which seems unnecessary, you may have a good case where a template will clean up your code.

Update: a better way to generalize the above statement:

When your source class will be used by objects of many different types, and the source class can interact with those types at a higher (more abstract) level, but your client classes want to interact with specific subtypes, that is a case for using templates. (Container/List classes being the well-known example).

share|improve this answer
    
this is very interesting and i never thought of applying TMP like that, only goes to show that i really need to learn it better and practice more. –  sap Nov 28 '11 at 21:42
    
I'm still trying to figure out the down votes here. I answered question directly and provided a concrete example of when a Template arises out of a refactoring. So what was wrong? –  Sam Goldberg Dec 29 '11 at 20:17
add comment

Just today, I used templates to implement a Finite State Machine to lex some input. Expression templates are extremely powerful tools for implementing code concepts like that- they run like hand-optimized C++ and are obscenely fast, yet very generic and very easy to write.

Generally speaking, templates make the most sense when implementing generic algorithms. If you're not implementing a generic algorithm, they don't make that much sense.

share|improve this answer
add comment

The most common uses of templates are as follows:

std::vector<int> vec;
std::map<int, float> mymap;

Then next common example is:

template<class T>
class MyArray {
public:
   virtual T get(int i) const=0;
};

Together with this kind of usage:

class ArrayImpl : public MyArray<float> {
public:
     float get(int i) const { }
};

That one showed important part of templates, which is type substitution -- T is replaced with float type in both places where it is used.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.