-1

How does the compiler know how obj looks like? It is not included in form.h, but it works anyway.

form.h

#ifndef FORM_H
#define FORM_H

template <class T>
class Form
{
public:
    Form(T* obj) {}
};

#endif // FORM_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    form = new Form<MainWindow>(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
Quentin
  • 62,093
  • 7
  • 131
  • 191
Ini
  • 548
  • 7
  • 19
  • I've answered as best I can, but this question is kind of unclear without a better description of which part of "what `obj` looks like" you're interested in. There are several interesting facets involved in this code and we don't know which ones you care about. – Lightness Races in Orbit Apr 23 '16 at 18:23

1 Answers1

2

The compiler knows what obj looks like because, as a T*, obj is a pointer and the compiler knows intimately what all pointers look like.

It doesn't need to know what T looks like, to deal with a T*.

If you were to dereference that pointer and use the T it points to, inside the class definition, then yes the definition of T would have to be available. But this is guaranteed to be true anyway because any code that instantiates Form<T> must already know, at the very least, that the chosen T is a class. Beyond that all the usual rules about forward-declarations apply.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055