4 ms·
On thing about forward declarations: they violate DRY. Now, most of the time, the trade off of repeating class Thing; is more than offset by faster build t
by cgrealy 6y ago
On thing about forward declarations: they violate DRY.
Now, most of the time, the trade off of repeating
class Thing;
is more than offset by faster build times.
But if
class Thing;
is actually
namespace Bob
{
namespace Dave
{
template <typename T>
class ThingTrait;
template <typename T>
class Thing : BaseClass<T, allocator<T>, trait<ThingTrait<T> >;
}
}
you really want to put that in it's own header, typically "Thing_fwd.h"
(apologies for any syntax errors, been a while since I've written C++)
- asdfasgasdgasdg 6y agoYou're either gonna write #include "thing.h" or class Thing; Either way, as a practical matter, you're saying, "There's something called Thing I'm going to use." C++ forces you to say that before use in each translation unit. It's not really "repeating" yourself to write it, since you haven't "said" it yet in this TU.
- cgrealy 6y agoYou are repeating yourself if you write class Thing; in every file that uses a Thing. And as I said, that's generally fine. The issue becomes when the declaration of Thing includes namespaces, template params, etc. Rewriting that is tedious and error prone. Look at something like std::string. That's actually namespace std { template< class T > struct allocator; template<class charT> struct char_traits; template<> struct char_traits<char>; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_string; using string = basic_string<char>; } No-one is forward declaring that.
- steerablesafe 6y agoI prefer _fwd headers for a different reason: it's easier to modify without breaking dependencies. If you change Thing to an alias to a class template specialization then all of the "class Thing;" forward declarations break.