I think "you must include all of the code in the header file" might be misleading. It's not necessarily true unless you need to use the templates in multiple source files. But unlike functions which you can just specify the function header which says how the function is to be called and leave the function body anonymous so that it doesn't need to recompile everything that calls it when the body changes, the body of templates needs to be fully known for its usage because the template arguments are supplemented at compile time. It's a form of
metaprogramming. Like Colin said, they are like macros on steroids.
- Code: Select all
template<class T>
class foo
{
public:
T var;
T get() { return var; }
};
foo<int> would
generate this class:
- Code: Select all
class foo
{
public:
int var;
int get() { return var; }
};
And, in case you're wondering, foo<ROCKETSAUCE> would generate this:
- Code: Select all
class foo
{
public:
ROCKETSAUCE var;
ROCKETSAUCE get() { return var; }
};
And the compiler would give you errors about ROCKETSAUCE not being defined (assuming it isn't) at T usages in the template class, and that's why templates can produce some of the most obscure errors ever.
But, one reason why they are different from macros is that they do give the compiler some more ability. Template usages of specific arguments will most likely generate the code only once and use it each time.