【问题标题】:invalid initializer for structured binding declaration结构化绑定声明的初始化程序无效
【发布时间】:2021-12-09 08:18:26
【问题描述】:

我应该如何解决这个错误?我应该改用const std::tuple<int, int, char> 吗?

constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36, 168, ' ' };

这会产生如下错误:

error: structured binding declaration cannot be 'constexpr'
  434 |         constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36, 168, ' ' };

 error: invalid initializer for structured binding declaration
  434 |         constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36, 168, ' ' };

Y_AxisLenX_AxisLen 应该是 int 类型,fillCharacter 应该是 char

【问题讨论】:

  • 第一个错误信息很清楚,你不能在这里使用constexpr。为什么你需要这些值是constexpr?也许让他们const就足够了?
  • @Some 程序员老兄切换到const 不会有什么不同。只有第一个错误会消失。
  • 为什么你需要结构化绑定而不是例如简单明了constexpr int Y_AxisLen = 36, X_AxisLen = 168; constexpr char fillCharacter = ' ';?不要过度考虑你的代码,或者仅仅因为它们是新的而使用新特性。 :)
  • @Some 程序员老兄 是的,这是一个有效的选择。我只是想让代码更紧凑一点。
  • 紧凑不是任何项目的目标。无论你是写这个还是长变体,你都可以被编译器生成完全相同的东西。

标签: c++ stdtuple structured-bindings


【解决方案1】:
  • 结构绑定现在不允许为constexpr
  • 结构绑定只能应用于以下情况。
    • 数组
    • 类似元组的
    • 结构数据成员

参考:https://en.cppreference.com/w/cpp/language/structured_binding

如果必须使用结构绑定,请使用std::make_tuple

const auto [ Y_AxisLen, X_AxisLen, fillCharacter ] = std::make_tuple(36, 168, ' ');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多