根据访问说明符使用特定重载函数的声明

nwp*_*nwp 5 c++

这段代码

struct Foo{
    void f(){
        f(0);
    }
private:
    void f(int){}
};

struct Bar : private Foo{
    using Foo::f;
};

int main() {
    Bar b;
    b.f();
}
Run Code Online (Sandbox Code Playgroud)

无法编译,因为Foo::f(int)private. 我不感兴趣Foo::f(int),我只是想要Foo::f()哪个public,所以我觉得应该有办法做到这一点。

我能想到一些解决方法:

  1. 重命名Foo::f(int)Foo::p_f(int),但这是多余的并且不允许重载解析f
  2. 实现需要对多个对象Bar::foo(){Foo::f();}进行大量复制/粘贴public f
  3. 继承publicly 并Foo邀请 UB 因为~Foo()不是virtual(也不应该是)
  4. 使所有fspublic很容易意外Foo损坏Bar

有办法说吗using public Foo::f;?或者使用其中一种没有相关缺点的解决方法?

Tem*_*Rex 0

如果您f(int)应该是private,并且永远不会成为公共 API 的一部分,那么您不应该关心将其重命名为fimpl

struct Foo{
    void f(){
        fimpl(0);
    }
private:
    void fimpl(int){}
};
Run Code Online (Sandbox Code Playgroud)

另一方面,如果f(int)是公共 API 的通用版本,并且您还想要一个具有特定值的便利包装器,则可以使用提供默认参数并创建f(int)成员public

struct Foo{
    void f(int = 0){}
};
Run Code Online (Sandbox Code Playgroud)

最后,如果您想要几个提供某些整数值的命名函数,那么我建议重命名这些包装器

struct Foo{
    void f(int) {} // general interface
    void sensible_name1() { f(0); }
    void sensible_name2() { f(1); } // etc.
}
Run Code Online (Sandbox Code Playgroud)