tags:

views:

283

answers:

5

I'm new to C++ Templates, and am finding it hard to understand and debug them. What are some good resources for doing both/either?

+9  A: 

I recommend the excellent book C++ Templates - The Complete Guide by Vandevoorde and Josuttis.

anon
+1  A: 

A template is simply a way of reducing the amount of code you need to write when developing classes.

For example the STL vector

std::vector<int> intList;
std::vector<float> floatList;

This will cause the compiler to actually make two classes behind the scenes, similar to if you copy and pasted the code but replaced all references to int with float.

Without templates you would need to create a vector class for each type you want to handle. There are more complex uses for classes but this is the easiest one to use, create & understand.

Once compiled the two sets of code for vector<int> and vector<float> are completely separate, but an IDE will step through the template class when debugging.

Steven
A: 

They are there for you to extend and modify as needed. Remember, it's a template, not a solution.

HTH

Andrew Sledge
+4  A: 

Alexandrescu is a wizard of templates. He has a lot of write-ups (many of which is freely available on his web-site and other sites) and some books.

Boost Documentation and Boost Cookbook is a good site to start with once you are comfortable with templates and feel like graduating to Boost.

dirkgently
A: 

I have two quick tips that may save you some problems in the future.

Templates must be defined and implemented in headers, because they are translated/created at compile-time

If you have the following code:

// Foo.h
template <typename T>
class Foo
{
    ...
};

// Bar.cpp
#include "Foo.h"
void func()
{
    Foo<int> fooInt;
    Foo<double> fooDouble;
}

When processing the Bar.cpp file, the compiler will "create" a new definition of the Foo class with every T replaced with the int type for the fooInt instance, and a new definition of the Foo class with every T replaced with the double type for the fooDouble instance.

In a nutshell, C++ does not support template classes, the compiler emulates them replacing the types at compile time and creating normal classes. So, the compiled type of fooInt and fooDouble are different.

Because they are translated at compile-time and not compiled individually, they must be defined and implemented in headers.

If you implement the template class as a normal class (header and source file) the error thrown by the compiler (the linker actually) is that there is no method implemented (it's because the source file is ignored).

You can still create forward declarations to avoid cyclic dependencies

It's just that you have to forward declare them like this:

template <typename T>
class Foo;

And, as with normal forward declarations, you have to be sure that you are including all the headers necessary.

Gastón