C++核心准则C.138:使用using为派生类生成重载函数集合‍

共 364字,需浏览 1分钟

 ·

2020-02-12 23:22



0c7ff733eee5c64fd753f4c12952fce3.webp

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

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

aecec1b431414f7157c1985aa6c6763a.webp


48fac5cc4c3fe529844e326c6640f4d1.webp

Reason(原因)

48fac5cc4c3fe529844e326c6640f4d1.webp


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

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

重载函数集合。


48fac5cc4c3fe529844e326c6640f4d1.webp

Example, bad(反面示例)

48fac5cc4c3fe529844e326c6640f4d1.webp


#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"
}

48fac5cc4c3fe529844e326c6640f4d1.webp

Example, good(范例)

48fac5cc4c3fe529844e326c6640f4d1.webp

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

Note(注意)

48fac5cc4c3fe529844e326c6640f4d1.webp

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
};
48fac5cc4c3fe529844e326c6640f4d1.webp

Enforcement(实施建议)

48fac5cc4c3fe529844e326c6640f4d1.webp

Diagnose name hiding

检出名称隐藏。


48fac5cc4c3fe529844e326c6640f4d1.webp

原文链接:

48fac5cc4c3fe529844e326c6640f4d1.webp

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




觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 68
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报