-1

I read that replacing

#include <SomeClass>

by

class SomeClass;

Might give some benefits, including speed up compilation time.

So I'm going over a Qt project and replacing all #include <Qt...> by class Qt...; on my project header files. But when I did that for QMap it returned

non-class template has already been declared as a class template”

What that means?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 1
    Forward declaration of template class need its template parameters, `template class QMap;` see [QMap](https://doc.qt.io/qt-5/qmap.html). – Jarod42 Feb 17 '21 at 11:24
  • 1
    fwiw, you cannot simply replace any include with a forward declaration. You will get other errors in places where a forward declaration is not sufficient. See here https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c – 463035818_is_not_an_ai Feb 17 '21 at 11:26
  • Care with forwarding 3rd library classes. Aliases, (new) default template parameters can come, and be problematic for maintenance or even depends of config/platform. – Jarod42 Feb 17 '21 at 11:28
  • So far I had trouble only with `QMap` and `QVector`, for all other `#include ` it looks like I can just replace and it seems to work – KcFnMi Feb 17 '21 at 11:45

1 Answers1

1

Forward declaration of class templates should be templated as well:

template <typename Key, typename T> 
class QMap;

Note that, until you include the proper header, those types are incomplete, and can be used in very limited ways. And if Qt were to add template arguments with defaults, assuming it wouldn't break code, it would break your forward declaration. It could be something simple, like adding an allocator type which defaults to std::allocator.

If your only concern is compilation speed, precompiled headers could serve you better.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • I thought I should do both, PCH and forward declarations. Why not? – KcFnMi Feb 17 '21 at 11:57
  • 1
    @KcFnMi if you are using precompiled headers, forward declarations won't affect the compilation time, since the headers are already compiled. They will help minimize dependencies, however. – Aykhan Hagverdili Feb 17 '21 at 11:59