如何在c++中模拟解构
How can I emulate destructuring in 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++中做些什么来获得类似的语法并模拟这种功能?
在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::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;
}
另一种可能是
#define DESTRUCTURE2(var1, var2, object) var1(object.var1), var2(object.var2)
可以这样使用:
struct Example
{
int foo;
int bar;
};
Example testObject;
int DESTRUCTURE2(foo, bar, testObject);
给出foo
和bar
的局部变量。
当然,它仅限于创建所有相同类型的变量,尽管我认为您可以使用auto
来解决这个问题。
这个宏只能做两个变量。因此,您必须创建DESTRUCTURE3、DESTRUCTURE4等等,以覆盖您想要覆盖的范围。
我个人不喜欢最后的代码风格,但它相当接近JavaScript特性的某些方面。
相关文章:
- 如何使用Google Mock来模拟gettimeofday()
- G锁定铸造到基础上会释放模拟行为
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- 落砂模拟碰撞检测C++和SFML
- 在gtest.中使用fff.h模拟系统API
- 谷歌模拟和覆盖关键字
- 用C#中的并集模拟C++嵌套结构
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 在模拟器中使用并集来模拟CPU寄存器有多合适
- 我写了一个C++程序来模拟Enigma机器.我没有得到输出
- 如何模拟不同边数的骰子滚动?
- 模拟持久按键
- 使用SIR模型的疾病爆发模拟
- 在 c++ 中模拟输入并在 JAVA 中读取它?
- 转发变量参数列表以模拟 std::thread
- 如何在谷歌模拟中匹配 C 样式数组
- 如何使用兰德随机化模拟点击
- 模拟GPS数据,以便使用Qt与Traccar一起使用
- QKeyPress - 在Qt中模拟按键
- 如何使用不同的谷歌模拟运行相同的谷歌测试用例?