C++中为什么不要将成员函数定义为模板虚函数

C++中为什么不要将成员函数定义为模板虚函数

本篇内容介绍了“C++中为什么不要将成员函数定义为模板虚函数”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

T.83:不要将成员函数定义为模板类型虚函数

Reason(原因)

C++ does not support that. If it did, vtbls could not be generated until link time. And in general, implementations must deal with dynamic linking.

C++不支持这么做。如果支持的话,只有到链接时才能生成虚函数表。一般情况下,C++语言的实现必须处理动态链接。

Example, don't(反面示例)

class Shape {
   // ...
   template<class T>
   virtual bool intersect(T* p);   // error: template cannot be virtual
};
Note(注意)

We need a rule because people keep asking about this

因为人们不断地问这个问题,因此我们需要这样一条规则。

Alternative(其他选项)

Double dispatch, visitors, calculate which function to call

双分发,访问者,通过调用函数进行计算。

Enforcement(实施建议)

The compiler handles that.

通过编译器处理这个问题。

“C++中为什么不要将成员函数定义为模板虚函数”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!