views:

286

answers:

4

Is it wise to have include guards around template classes?

Aren't template classes supposed to be reparsed each time you reference them with a different implementation?

N.B In Visual C++ 2008 I get no errors combining the two...

+6  A: 

Templates definitions are supposed to be parsed once (and things like two phases name lookup are here so that as much errors as possible can be given immediately without having an instantiation). Instantiations are done using the internal data structure built at that time.

Templates definitions are usually (i.e. if you aren't using export or doing something special) in header files which should have their include guard. Adding one for template definition is useless but not harmful.

AProgrammer
Do add include guards always, get used to it, as it is a GOOD practice.
Poni
If you do any development on win32, include `#pragma once` whenever using include guards.
KitsuneYMG
+10  A: 

You need include guards. Consider this code:

// this is t.h
template <typename T>
void f( T t ) {
}

// this is t.cpp
#include "t.h"
#include "t.h"

int main() {
    f( 1 );
}

This gives the error:

t.h:2: error: redefinition of 'template<class T> void f(T)'
t.h:2: error: 'template<class T> void f(T)' previously declared here

Also, the headers that contain templates routinely also contain non-template code.

anon
Strictly that's a template function rather than a template class, but the principle is the same - you get a multiple definition error if you declare the same class twice, template or not.
Mike Dimmick
+2  A: 

Short answer: Every unit you plan to include more than once with any definitions should have a header guard. That is with or without templates.

daramarak
+2  A: 

To answer your first question: Yes, it is wise, and mandatory, to have include guards around template classes. Or more strictly surrounding the entire contents of every header file.

This is the way to obey the One Definition Rule when you have stuff in header files, so that its shared around and still safe. There may be other header files that include yours. When the compiler compiles a module file, it may see a #include of your header file many times, but the guards kick-in on the second and subsequent times to make sure the compiler only sees the contents once.

Its doesn't matter that the compiler reparses anything; that's its job. You just have to supply the contents once and then the compiler has seen it and can refer to it again as many times as it needs.

quamrana