C++核心准则T.83:不要将成员函数定义为模板虚函数

时间:2022-07-26
本文章向大家介绍C++核心准则T.83:不要将成员函数定义为模板虚函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

T.83: Do not declare a member function template virtual

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.

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

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t83-do-not-declare-a-member-function-template-virtual