Tre*_*key 35 javascript c++ language-construct destructuring c++17
在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 + '!')
Run Code Online (Sandbox Code Playgroud)
我可以在C++中做些什么来获得类似的语法并模拟这种功能?
Esc*_*alo 38
对于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;
Run Code Online (Sandbox Code Playgroud)
我完全不像你提出的那样,没有意识到符号的方法.
dal*_*lle 31
在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";
}
Run Code Online (Sandbox Code Playgroud)
主要是std::map和std::tie:
#include <iostream>
#include <tuple>
#include <map>
using namespace std;
// an abstact object consisting of key-value pairs
struct thing
{
std::map<std::string, std::string> kv;
};
int main()
{
thing animal;
animal.kv["species"] = "dog";
animal.kv["sound"] = "woof";
auto species = std::tie(animal.kv["species"], animal.kv["sound"]);
std::cout << "The " << std::get<0>(species) << " says " << std::get<1>(species) << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)