如何在c++中模拟解构

How can I emulate destructuring in C++?

本文关键字:模拟 c++      更新时间:2023-10-16

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

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

对于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;

主要与std::mapstd::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;
}

另一种可能是

#define DESTRUCTURE2(var1, var2, object) var1(object.var1), var2(object.var2)

可以这样使用:

struct Example
{
    int foo;
    int bar;
};
Example testObject;
int DESTRUCTURE2(foo, bar, testObject);

给出foobar的局部变量。

当然,它仅限于创建所有相同类型的变量,尽管我认为您可以使用auto来解决这个问题。

这个宏只能做两个变量。因此,您必须创建DESTRUCTURE3、DESTRUCTURE4等等,以覆盖您想要覆盖的范围。

我个人不喜欢最后的代码风格,但它相当接近JavaScript特性的某些方面。