Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Jan 10, 2015 #1
    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?
  2. jcsd
  3. Jan 11, 2015 #2
  4. Jan 11, 2015 #3
    Either I am misunderstanding, or this doesn't relate to the question?

    As far as I can tell it explains the difference between declaration and definition and makes no comment as to why forward declaring a template is frowned on.
  5. Jan 11, 2015 #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.
  6. Jan 19, 2015 #5

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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).
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook