简体   繁体   中英

Runtime binding and template instantiation

As you can see from here not all template functions are being compiled in a template class. Standard says, that if the method or a member is not being used, it is not being compiled. Cool feature, indeed! Now, lets discuss the following hierarchy:

class A
{
  virtual void f() {};
};

template <typename T>
class B : public A
{
  virtual void f () override
  {
       // do something dangerous
  }
}

You will never know if B<int>::f is being called, right? The reason is that you can call a function B::f with dynamic binding and you never know if A* points onto B type object or other typed object that is derived from A . So how the compiler should handle this case?

A* ptr = nullptr;
if (i > 0)
{
    ptr = new B<int>();
}
ptr->f();

How does compiler guess/spot this case to generate B<int>::f

IMPORTANT RELATED QUESTION: Can a C++ class member function template be virtual?

Somewhere in your program you have to use B<int> or a type derived there of to create an instance. At that point the template is instantiated and the code for it is generated. There is also explicit instantiation. Check out cppreference.com for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM