C++核心准则C.138:使用using为派生类生成重载函数集合
发布日期:2021-07-01 05:27:05 浏览次数:2 分类:技术文章

本文共 1473 字,大约阅读时间需要 4 分钟。

C.138: Create an overload set for a derived class and its bases with using

C.138:使用using为派生类生成重载函数集合‍

 

Reason(原因)

Without a using declaration, member functions in the derived class hide the entire inherited overload sets.

如果不使用using声明,派生类中的成员函数会隐藏整个继承来的

重载函数集合。

 

Example, bad(反面示例)

#include 
class B {public:    virtual int f(int i) {        std::cout << "f(int): "; return i;     }    virtual double f(double d) {        std::cout << "f(double): "; return d;     }    virtual ~B() = default;};class D: public B {public:    int f(int i) override     {        std::cout << "f(int): "; return i + 1;     }};int main(){    D d;    std::cout << d.f(2) << '\n';   // prints "f(int): 3"    std::cout << d.f(2.3) << '\n'; // prints "f(int): 3"}

 

Example, good(范例)

class D: public B {public:    int f(int i) override     {        std::cout << "f(int): "; return i + 1;     }    using B::f; // exposes f(double)};

 

Note(注意)

This issue affects both virtual and nonvirtual member functions

For variadic bases, C++17 introduced a variadic form of the using-declaration,

本条款对虚函数和非虚函数都有效。对于可变基类,C++17引入using声明的可变形式。

template 
struct Overloader : Ts... {    using Ts::operator()...; // exposes operator() from every base};

 

Enforcement(实施建议)

Diagnose name hiding

检出名称隐藏。

 

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c138-create-an-overload-set-for-a-derived-class-and-its-bases-with-using

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

转载地址:https://oothinking.blog.csdn.net/article/details/105371538 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:ARM C++交叉编译环境构建方法
下一篇:c++核心准则C.137: 使用虚基类避免过于一般的基类

发表评论

最新留言

不错!
[***.144.177.141]2024年04月11日 12时44分32秒