且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一个C ++类的成员函数模板可以是虚拟的吗?

更新时间:2022-12-24 19:32:04

模板都是关于编译器在编译时生成代码的。虚拟函数都是关于运行时系统确定在运行时调用的函数

Templates are all about the compiler generating code at compile-time. Virtual functions are all about the run-time system figuring out which function to call at run-time.

一旦运行时系统确定需要调用模板化的虚拟函数,编译就完成了,编译器不能再生成相应的实例了。因此,您不能有虚拟成员函数模板。

Once the run-time system figured out it would need to call a templatized virtual function, compilation is all done and the compiler cannot generate the appropriate instance anymore. Therefore you cannot have virtual member function templates.

但是,有一些强大而有趣的技术源于组合多态性和模板,特别是所谓的 类型擦除

However, there are a few powerful and interesting techniques stemming from combining polymorphism and templates, notably so-called type erasure.