The effect of virtual on the use of a class template member

I (vaguely) know that a template is not created if not used. For example, the following code will compile even if T::type does not make sense when T = int .

 template<typename T> struct A { void f() { using type = typename T::type; } }; A<int> a; //ok 

It compiles because f() not used, so no instance is created - thus, the reality of T::type remains uncontrollable. It doesn't matter if any other member function g() calls f() .

 template<typename T> struct A { void f() { using type = typename T::type; } void g() { f(); } //Is f() still unused? }; A<int> a; //ok 

It also compiles fines . But here I am aware of the nebula in my understanding of the definition of "use." I'm asking:

  • Is f() still unused? How exactly?

I can clearly see that it is used inside g() . But then I thought that since g() not used, f() also not used, in terms of instantiating. This seems reasonable enough. still.

However, if I add the virtual to g() , it does not compile:

 template<typename T> struct A { void f() { using type = typename T::type; } virtual void g() { f(); } //Now f() is used? How exactly? }; A<int> a; //error 

The result is a compilation error , because now it is trying to create an instance of f() . I do not understand this behavior.

Can anyone explain this? Especially the influence of the virtual on the definition of "use" of a class template member.

+10
c ++ instantiation c ++ 11 virtual templates
Oct 28 '13 at 8:32
source share
1 answer

A quick look at 3.2 [basic.def.odr] gives:

3 / [...] A virtual member function is used by odr if it is not pure. [...]

And I also found in 14.7.1 [temp.inst]:

10 / An implementation shall not implicitly create a function template, a member template, a non-virtual member function, a member class, or a static data element of a class template that does not require instantiation. It is not known whether the implementation implicitly implements an instance of a virtual member function of a class template if the virtual member function were not otherwise implemented. (highlighted by me)

So ... I would say that it is likely that the virtual method will always be created.

In pragmatic terms, I expect the compiler to create a virtual template class table when it instantiates the class; and thus instantly create an instance of all virtual member functions of this class (therefore, it can refer to those from the virtual table).

+8
Oct 28 '13 at 8:46
source share



All Articles