必须为非常量别名,默认参数为常量

问题描述 投票:1回答:1

我们如何使用其默认参数编码必须为非常量的别名参数,因为它不能引用,因此必须为常量?并且必须没有过载功能,因为它的91行长

Bar {
  int on;
  Bar(){};
  Bar(bool o): off{o}{}
  bool off; 
}

int fooBar(int board, Bar& bar = static_cast<Bar>(1)) {

//...
}

gcc给了

错误:无法将'Bar&'类型的非常量左值引用绑定到'Bar'类型的右值

如何解决-有明确的解释-这样的人?

c++ c++17 constants bind
1个回答
0
投票

您发现此错误的原因是,您已经发现,非const引用必须绑定到左值:也就是说,它必须绑定到具有名称的对象。临时文件不会绑定到非const引用:仅绑定到const Bar&Bar&&,而您都不想要。

这给我们几个选择。

我个人最喜欢的是根本不使用默认参数,而要提供重载:

int fooBar(int board, Bar& bar) {
  // ...
}

int fooBar(int board) {
  // to save code duplication you can call in fooBar
  Bar b{1};
  return fooBar(board, b);
}

我认为这是最简单,最一致的选择。

其他可能性包括:

  • 制作一个全局变量,其唯一目的是作为默认参数(糟糕,并且干扰多线程):
    inline Bar default_bar;
    int fooBar(int board, Bar& bar = default_bar) {
      // ...
    }
    
  • 改用指针,但要注意,您必须检查它们是否提供了参数:
    int fooBar(int board, Bar* bar = nullptr) {
      // ..., but make sure to test bar!
    }
    
  • 或以其他方式使用std::optional<std::reference_wrapper<Bar>>或类似类型。
© www.soinside.com 2019 - 2024. All rights reserved.