一个C ++类的成员函数模板可以是虚拟的吗? [英] Can a C++ class member function template be virtual?

查看:165
本文介绍了一个C ++类的成员函数模板可以是虚拟的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说C ++类的成员函数模板不能是虚拟的。这是真的?

I have heard that C++ class member function templates can't be virtual. Is this true?

如果它们可以是虚拟的,那么什么是使用这样的函数的场景的示例?

If they can be virtual, what is an example of a scenario in which one would use such a function?

推荐答案

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

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.

这篇关于一个C ++类的成员函数模板可以是虚拟的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆