c++ - 如何在 C++ 中模拟解构?

标签 c++ c++17 destructuring language-construct

在 JavaScript ES6 中,有一个称为 destructuring 的语言功能。 .它也存在于许多其他语言中。

在 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++ 中做什么来获得类似的语法并模拟这种功能?

最佳答案

在 C++17 中,这称为 structured bindings ,它允许以下内容:

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";
}

关于c++ - 如何在 C++ 中模拟解构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31394507/

相关文章:

c++ - 在 C++ 中接受基于线程表现不同的套接字包括

javascript - 具有解构数组默认参数的函数的非数组参数给出 TypeError

c++ - 在 C++ 中返回一个带有指针成员变量的对象

c++ - 有没有办法将 'std::vector 2d' 作为指向 '2d c array' 的指针传递给函数

c++ - 从自动输入参数推导出返回类型

c++ - Clang 和二进制折叠表达式——空参数包的诅咒

javascript - 函数中的JavaScript可选解构参数

javascript - JavaScript 1.7 中的解构

C++标准,重载函数解析/匹配

c++ - 当 min 和 max 为正时,Rand() 返回负数