如何在 C 中模拟解构?

新手上路,请多包涵

在 JavaScript ES6 中,有一种称为 解构 的语言特性。它也存在于许多其他语言中。

在 JavaScript ES6 中,它看起来像这样:

 var animal = {
    species: 'dog',
    weight: 23,
    sound: 'woof'
}

//Destructuring
var {species, sound} = animal

//The dog says woof!
console.log('The ' + species + ' says ' + sound + '!')

我可以在 C++ 中做什么来获得类似的语法并模拟这种功能?

原文由 Trevor Hickey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 399
2 个回答

对于 std::tuple (或 std::pair )对象的具体情况,C++ 提供了 std::tie 函数,看起来类似:

 std::tuple<int, bool, double> my_obj {1, false, 2.0};
// later on...
int x;
bool y;
double z;
std::tie(x, y, z) = my_obj;
// or, if we don't want all the contents:
std::tie(std::ignore, y, std::ignore) = my_obj;

我不知道与您呈现的符号完全一样的方法。

原文由 Escualo 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 C++17 中,这称为 结构化绑定,它允许执行以下操作:

 struct animal {
    std::string species;
    int weight;
    std::string sound;
};

int main()
{
  auto pluto = animal { "dog", 23, "woof" };

  auto [ species, weight, sound ] = pluto;

  std::cout << "species=" << species << " weight=" << weight << " sound=" << sound << "\n";
}

原文由 dalle 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题