[C++] When is it OK to forward declare templates?

  • #1
90
19

Main Question or Discussion Point

This has been bugging me for a while. I suspect the answer is in Sutter or Meyers but I don't own them. Why do so many of the top C++ people say forward declaring templates is bad style or dangerous?
 

Answers and Replies

  • #3
90
19
  • #4
90
19
I have since found the answer by using Google which returned Google's C++ style guide which explains why they don't allow it: Forward declaring a template creates code duplication which prevents the header's owner from making compatible changes to the template.
 
  • #5
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
I have since found the answer by using Google which returned Google's C++ style guide which explains why they don't allow it: Forward declaring a template creates code duplication which prevents the header's owner from making compatible changes to the template.
That's a lousy excuse. There is a way around that excuse: The author of the template writes another header where the template is forward declared. Note that the C++ library does this, but only with the C++ I/O. If you have a list as a data member of some class, you need the full implementation anyhow.

There is a good reason for not forward declaring templates in your code defined in the standard library. It's illegal, and it's the worst kind of illegal. It's undefined behavior. The standard makes this very explicit. It might work on your computer with your current version of your compiler. Go to a different machine, or a different compiler, and it might not work. Heaven forbid, it might even create nasal demons.

There is a way around the difficulties of forward declaring templates, and that's the PIMPL idiom (aka the handle/body implementation). You hide all the details of the implementation (including member data) in a separate class. The public class is very simple. It comprises public member functions and a single private data member. That private data member is a pointer to that separate class where all the work is done, all the data are stored (except for the handle, of course).
 

Related Threads on [C++] When is it OK to forward declare templates?

  • Last Post
Replies
3
Views
502
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
1
Views
2K
Replies
2
Views
4K
Replies
10
Views
7K
Replies
1
Views
4K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
6
Views
4K
Top