- #1
Carno Raar
- 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?
.Scott said:I suggest this article:
http://warp.povusers.org/programming/template_declarations.html
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.Carno Raar said: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.
Forward declaration for templates should be used when you want to declare a template class or function without defining its implementation. This can be useful in cases where the template is not fully utilized or when you want to reduce compile time by avoiding unnecessary header file inclusion.
No, not all templates can be forward declared. Only templates with non-dependent types can be forward declared. Templates with dependent types, such as those that use the typename
keyword, cannot be forward declared.
To forward declare a template class, you need to specify the template parameters in angle brackets after the class name. For example, template <typename T> class MyClass;
This will declare a template class named MyClass
with a single template parameter T
.
Forward declaration for templates can reduce compile time by avoiding unnecessary header file inclusion. It can also help to reduce code dependencies and improve modularity by separating the declaration and implementation of templates.
One drawback of using forward declaration for templates is that it can make the code more complex and difficult to understand. It may also require additional effort to maintain and update the code in the future. Additionally, forward declaration may not be suitable for all situations and may not always result in a significant improvement in compile time.