如何在C ++中模拟解构? [英] How can I emulate destructuring in C++?
本文介绍了如何在C ++中模拟解构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript ES6中,有一种称为解构的语言功能。
In JavaScript ES6, there is a language feature known as destructuring. It exists across many other languages as well.
在JavaScript ES6中,它如下所示:
In JavaScript ES6, it looks like this:
var animal = {
species: 'dog',
weight: 23,
sound: 'woof'
}
//Destructuring
var {species, sound} = animal
//The dog says woof!
console.log('The ' + species + ' says ' + sound + '!')
我可以在C ++中做些什么来获得类似的语法并模仿这种功能?
What can I do in C++ to get a similar syntax and emulate this kind of functionality?
推荐答案
std :: tie
看起来很相似:
For the specific case of std::tuple
(or std::pair
) objects, C++ offers the std::tie
function which looks similar:
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;
我不知道一种符合你的方法。
I am not aware of an approach to the notation exactly as you present it.
这篇关于如何在C ++中模拟解构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文