模板化虚拟函数 [英] Templatized Virtual function

查看:117
本文介绍了模板化虚拟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道C ++不允许类中的模板化虚拟函数。任何人都明白为什么会有这样的限制?

We know that C++ doesn't allow templated virtual function in a class. Anyone understands why such restriction?

推荐答案

简单答案:虚拟函数不知道谁调用谁,直到运行时,从已经编译的一组候选函数中选择一个函数。函数模板OTOH是在编译时从调用方创建任意数量的不同函数(使用在编写被调用方时可能甚至不知道的类型)。这只是不匹配。

Short answer: Virtual functions are about not knowing who called whom until at run-time, when a function is picked from an already compiled set of candidate functions. Function templates, OTOH, are about creating an arbitrary number of different functions (using types which might not even have been known when the callee was written) at compile-time from the callers' sides. That just doesn't match.

稍微长一点的答案:虚函数是使用额外的间接(程序员的通用多用途固化)实现的,通常实现为一个函数指针表虚函数表,通常缩写为vtable)。如果你调用一个虚函数,运行时系统将从表中选择正确的函数。如果有虚拟函数模板,运行时系统将必须找到具有确切模板参数的已编译模板实例的地址。因为类的设计器不能提供任意数量的从无限制的可能参数创建的函数模板实例,所以这不能工作。

Somewhat longer answer: Virtual functions are implemented using an additional indirection (the Programmer's General All-Purpose Cure), usually implemented as a table of function pointers (the so-called virtual function table, often abbreviated "vtable"). If you're calling a virtual function, the run-time system will pick the right function from the table. If there were virtual function templates, the run-time system would have to find the address of an already compiled template instance with the exact template parameters. Since the class' designer cannot provide an arbitrary number of function template instances created from an unlimited set of possible arguments, this cannot work.

这篇关于模板化虚拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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