2

The following code will fail

class InComplte;
void f() {
    new InComplte();
}
class InComplte {

};

Because it is newing an incomplete type. But if template is used, the following code can compile

template<typename T>
class CComCoClass {
    public:
    static void create_di(T**p) {
        *p = new T();
    }

};

class Book: public CComCoClass<Book> {
public:
int i = 3;

};

The base class CComCoClass seems to be newing an incomplete type. Why the Book can inherit a base class that creates it?

EvanL00
  • 370
  • 3
  • 13
  • 4
    Member functions of class templates are not instantiated until they are actually used. So it depends in which context `create_di` will be instantiated. If it is instantiated in the context when `T` becomes a complete type, it will work. If you try to instantiate it before that, it will fail like your first example. – Evg Mar 17 '22 at 08:34
  • 1
    @Evg Thanks! Your comment is quite clear and I get it now. – EvanL00 Mar 18 '22 at 03:23

1 Answers1

1

A member function of a class template is not evaluated when the class template is instantiated. The functions instantiation is delayed until it is called. create_di isn't called in the example, so it isn't evaluated.

eerorika
  • 232,697
  • 12
  • 197
  • 326