On 10/24/2019 10:57 AM, Robert M. Münch wrote:

> Unfortunately, member function template instances are never virtual
> functions, so you can't override them."
>
> Is there a reason why these type of functions are not virtual or can't
> be made virtual?

One practical reason is, the number of their instances cannot be known when the interface (or base class) is compiled.

interface I {
  void foo();
  void bar();
}

When the compiler compiles that interface, it generates a vtbl (virtual function pointer table) with 2 entries in it. (As usual, those entries are indexed by 0 and 1.)

class C : I {
  // ...
}

When compiling the above class, the compiler generates a vtbl for C, and populates the entries with addresses of C.foo and C.bar.

  obj.bar();

When compiling the above code, compiler uses the equivalent of the following:

  obj.vtbl[1]();

In the case of member function templates, because the number of their instances are not known, the compiler cannot know how many entries to have in such an interface's vtbl. (Note that the compilation of I and C would ordinarily be separate from the calling code.)

  obj.someTemplate(42);

Which vtbl entry corresponds to the 'int' instance?

  obj.vtbl[???]();

This cannot be known as different compilation units instantiate templates according to their own uses. There is no common place to determine the length and entries of vtbls of I and C.

Ali


Reply via email to