2

I have been doing forward declarations in header files, and including the actual class files in cpp. But I run into problems when the classes are templated:

class MyClass {
public:
  MyClass();
  void aFunction();
private:
  QList<int> m_member;
};

To get it to build I need to give this class info about QList. I tried:

class QList;

error: template argument required for 'class QList'

I tried (because I will only need QList of integers in this particular class):

class QList<int>;

error: specialization of 'QList<int>' after instantiation

I have looked up these errors but found only issues with people having trouble creating class templates, found nothing about forward declarations.

If nothing else works, I can #include <QList> in the header file and give up on forward declaration - but I would like to understand this issue.

This option is also suggested in the most popular question about template classes forward declarations:

Just #include <list> and don't worry about it.

I don't understand other answers...

Community
  • 1
  • 1
Thalia
  • 13,637
  • 22
  • 96
  • 190
  • 1
    If you want to have `QList` as a member of your class, the full declaration is needed anyway (because the compiler will need to compute the size of your class). With a forward declaration you can have pointers or references, but not much more. – Bo Persson Aug 17 '15 at 15:36
  • @BoPersson how can it do that if the size of the list is not known ? – Thalia Aug 17 '15 at 15:37
  • 1
    The `QList` object will always be of the same size. The `int`s in the list will be allocated separately. – Bo Persson Aug 17 '15 at 15:40
  • The compiler errors you quote sound like `` has already been included, actually, so it won't hurt to include it again. – aschepler Aug 17 '15 at 18:06

1 Answers1

1

You can forward declare a templated class, like this:

template<typename>
class QList;

But it wont work if you declare a member with this type (i.e. m_member) that is not a reference or a pointer.

imreal
  • 10,178
  • 2
  • 32
  • 48
  • Oh so if I want this my private members need to be references... hat would work... would I have to declare them as `QList*m_list` ? – Thalia Aug 17 '15 at 15:39
  • @Thalia, right (pointer or reference), because just like with any forward declaration, it does not define a complete type. – imreal Aug 17 '15 at 15:40