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

  • C/C++
  • Thread starter Carno Raar
  • Start date
  • Tags
    c++
The handle is simply a pointer to that class. This separates the interface from the implementation, so you can change the implementation without changing the interface.f
  • #1
90
19
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?
 
  • #4
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
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).
 

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

Back
Top