开发者

Template classes and include guards in C++

开发者 https://www.devze.com 2022-12-22 01:32 出处:网络
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?

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 I开发者_StackOverflow中文版n Visual C++ 2008 I get no errors combining the two...


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号