I spend some time examining boost::
libraries architecture and was interested with the following fact:
In some parts of the libraries a yyy_fwd.hpp
idea is used pretty common (see boost/detail
or boost/flyweight
for examples).
These files obviously contain only forward declarations of some template-based classes and as far as I understand, could benefit in terms of compilation time.
Could someone point out in what cases do they help and should I use 开发者_JAVA技巧the same idea when designing my own templates?
Thank you.
Forward declarations are needed to reduce compile-time dependencies. For instance, when implementing Pimpl idiom.
One more case is that, for instance, boost::pool
* depends on windows.h
on Windows platform. When creating my interface I don't want to force the users of my class to include the system headers by using my interface.
*Ok, that's a bad example, because boost/poolfwd.hpp
still includes windows.h
, but I hope they'll fix this issue. And I hope you get the idea.
I don't know about boost, but these forward declarations also exist in the standard library. For example, <iosfwd>
contains forward declarations for streams (which are templates, normally hidden behind typedefs).
You'd benefit from this header, when declaring an overloaded operator<<.
In your header:
#include <iosfwd>
class X { ... };
std::ostream& operator<< (std::ostream& os, const X& x);
Note that the header doesn't require the full definition of ostream
(= basic_ostream<char, char_traits<char> >
).
The rationale for the header is that those templates are cumbersome to forward declare yourself. For the above example, it would look something like:
namespace std {
template <class CharT>
class char_traits;
template <class CharT, class CharTraits>
class basic_ostream;
typedef basic_ostream<char, char_traits<char> > ostream;
}
精彩评论