gpt4 book ai didi

c++ - 使用基于访问说明符的特定重载函数的声明

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:24:40 24 4
gpt4 key购买 nike

这段代码

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

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

int main() {
Bar b;
b.f();
}

fails to compile因为 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 的大量复制/粘贴>s
  3. Foo 继承 public,它邀请 UB,因为 ~Foo() 不是 virtual(并且是不应该的)
  4. 将所有 f 设为 public 使得很容易意外破坏 FooBar

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

最佳答案

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

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

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

struct Foo{
void f(int = 0){}
};

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

struct Foo{
void f(int) {} // general interface
void sensible_name1() { f(0); }
void sensible_name2() { f(1); } // etc.
}

关于c++ - 使用基于访问说明符的特定重载函数的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com