1 classFaux2 {3 Public:4Template <typename t>5 Virtual void Do()//member function templates cannot be virtual6 {}7 };8 9 TenTemplate <typename t> One classvrai A { - Public: - Virtual void Do(T v)//ok! the {} -};
Why not in the faux?
Because if virtual function is a template, class faux will have a lot of do:do<int>,do<string>, depending on the different types used.
C + + requires that the faux memory layout be determined before faux is instantiated (unsure how to allocate memory?). But if virtual function is a template, there may be an indeterminate number of do<> in later use, meaning that the virtual functions table cannot be determined, that is, the faux memory layout is not determined. For example, an example of faux:
new Faux ().
Ff-> Do("Hi");//Do<string>, huh? The virtual function table adds a virtual void do<string>... ...... FF (f)- Do(9527);//Do<int>, huh? The virtual function table adds a virtual void do<int>//Oh, wait, not that when the FF is instantiated, the memory layout (including the virtual function table) has to be determined? Call a function to add a virtual function, which violates the rule. //Why does the virtual function table have to be determined? Dynamic add not very cool? C + + compiler in advance parse it all over again? //since the compiler compiles each CPP regardless of the other CPP, it only cares about its own compilation unit. References between different compilation units that's the linker thing. //if A.cpp B.cpp also contains the class Faux {...}; //when the compiler compiles A.cpp, several virtual function table entries are added, and when the compiler compiles the B.cpp, several virtual function table entries are added, and then a conflict occurs. //even if it does not conflict, first compiled A.cpp increased by 1, 2, and then compiled B.cpp 3, 4 items, then a.obj it appears that the virtual function table of faux only two, and B.obj appears faux virtual function table has 4 items. //this is inconsistent. therefore, in order to avoid these problems, it is required that the virtual function table size is determined before the object is instantiated. Why vrai? Since vrai is a template class, his instantiation will not be determined until it is used specifically. But no matter which instance vrai<int> or vrai<string> their virtual function table is always determined by only one virtual do.
Template classes & Virtual functions