【问题标题】:Specifying an in-class using-declaration targeting different functions with the same name指定针对具有相同名称的不同函数的类内使用声明
【发布时间】:2020-01-22 02:55:17
【问题描述】:

当使用 using 声明来公开基类的方法时,如何才能公开具有相同名称但不同参数的方法?

class Base
{
protected:
    void f();
    void f(int);
};

class Derived: public Base
{
    using Base::f; // which is exposed, and how can I manually specify?
};

【问题讨论】:

    标签: c++ syntax using-declaration


    【解决方案1】:

    这样,基类中的所有方法都会暴露出来,如果你只想使用派生类中的特定方法,你需要使用forwarding function

    class Base{
      protected:
      void f();
      void f(int);
    };
    
    class Derived: public Base
    {
     public:
      void f()    //forwarding function
      {
        Base::f();
      }
    };
    

    有关此方法的更多说明,您可以阅读 Scott Meyers 的第一本书,专门用于避免隐藏继承名称的项目(link 到此项目)

    【讨论】:

    • 这似乎是一个非常 hacky 的解决方案,尽管我猜这种感觉在 C++ 语言中很常见。你知道这是否真的会导致一个单独的函数被发出吗?是否比我只为基类方法指定另一个名称的成本更高?
    • @invertedPanda,该函数将被隐式内联,所以我猜这不会对您的程序造成任何成本
    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多