【问题标题】:c++ aggregates initialization with c-style arraysc++ 使用 c 样式数组聚合初始化
【发布时间】:2019-01-31 16:22:58
【问题描述】:

在 c++14 中,我有以下类型:

std::tuple<int[2], int>;

如何正确初始化它?这个

std::tuple<int[2], int> a {{2,2},3};

给我这个错误:

/usr/include/c++/5/tuple:108:25: 错误:数组用作初始化器

此时:

std::tuple<std::array<int,2>, int> a {{2,2},3};

可行,但我希望能够使用标准 C 样式数组

【问题讨论】:

  • 为什么需要原始数组? std::array&lt;int,2&gt; 解决了这个问题并且更容易使用。如果您担心速度或效率,请注意 std::array 是零成本抽象,只要您通过优化进行编译,您就会得到相同的汇编代码。
  • std::tuple 不可聚合,int[2] 不可复制:-/ ...
  • @NathanOliver,我同意你的看法。我必须使用使用它们的现有代码,所以我试图看看是否有其他方法

标签: c++ stdarray stdtuple


【解决方案1】:

std::tuple 不是聚合,也不提供list-initializer constructor。这使得该类型的列表初始化无法用于 C 数组。

但是你可以使用std::make_tuple:

auto a = std::make_tuple<int[2], int>({2,2},3);

【讨论】:

  • std::make_tuple&lt;int[2]&gt;({2,2},3); :)。而make_* 通常是让编译器推断类型...
  • @Jarod42 这很奇怪。不会使用;)
  • 类型原来是std::tuple,所以很遗憾我们还没有。
猜你喜欢
  • 2017-07-01
  • 2021-10-23
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
相关资源
最近更新 更多