设为首页 加入收藏

TOP

结构体自动化转为char数组(三)
2014-04-06 17:36:02 来源: 作者: 【 】 浏览:338
Tags:结构 自动化 转为 char 数组

 

  再看看测试代码:

  //嵌套的结构体

  struct MySubStruct

  {

  int a;

  double b;

  auto Get()->decltype(std::make_tuple(a, b))

  {

  return std::make_tuple(a, b);

  }

  };

  //含指针和嵌套结构体的结构体

  struct MyStruct

  {

  int a;

  double b;

  int count; //对于指针,必须将指针元素个数count放在指针元素的前面

  int* p;

  MySubStruct t;

  auto Get()->decltype(std::make_tuple(a, b, count, p, t))

  {

  return std::make_tuple(a, b, count, p, t);

  }

  };

  //嵌套结构体指针的结构体

  struct MyStruct2

  {

  int a;

  double b;

  int count;//对于指针,必须将指针元素个数count放在指针元素的前面

  MySubStruct* t;

  auto Get()->decltype(std::make_tuple(a, b, count, t))

  {

  return std::make_tuple(a, b, count, t);

  }

  };

  //含void指针的结构体

  struct MyStruct3

  {

  bool r;

  int a;//对于指针,必须将指针元素个数count放在指针元素的前面

  void* b;

  auto Get()->decltype(std::make_tuple(r,a, b))

  {

  return std::make_tuple(r, a, b);

  }

  };

  //含字符串的结构体

  struct MyStruct4

  {

  int a;

  string b;

  auto Get()->decltype(std::make_tuple(a, b))

  {

  return std::make_tuple(a, b);

  }

  };

  void TestArray()

  {

  MyStruct t = { 9, 1.256, 2, new int {3, 4}, {14, 5.36} };

  char buf[100];

  Put(buf, sizeof(buf), t);

  char buf1[100];

  MySubStruct* st = new MySubStruct ;;

  st[0] = { 6, 7 };

  st = { 8, 9 };

  MyStruct2 t2 = { 3, 4, 2, st };

  Put(buf1, sizeof(buf1), t2);

  int* p3 = new int {5,6};

  MyStruct3 t3 = { false, 2, (void*) p3 };

  char buf3[100];

  Put(buf3, sizeof(buf3), t3);

  MyStruct4 t4 = { 6, "test" };

  char buf4[100];

  Put(buf4, sizeof(buf4), t4);

  }

  可以看到不管结构体有多少字段,还是是否含有字符串、指针或者嵌套了结构体,都可以通过一个Put函数搞定,没有了繁琐而又重复的赋值和偏移操作,不用担心偏移错了,整个繁琐的过程程序都自动化的完成了,简单利落。

  要用这个自动化的将结构体转换为char数组的功能有一点约束条件:

  每个结构体需要提供一个Get函数返回元信息;

  结构体字段如果为指针的话,必须要将指针元素个数放到该字段前面;数组的话也需要提供数组元素个数的字段,因为Get函数会将数组转为指针,数组长度信息会丢掉。

  我觉得这个约束条件相对于它实现的自动化的转换的便利性来说是几乎可以忽略的负担,是微不足道的。

        

首页 上一页 1 2 3 4 5 下一页 尾页 3/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++非类型模板参数 下一篇关于构造函数c++

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C语言指针从入门到基 (2025-12-26 05:21:36)
·【C语言指针初阶】C (2025-12-26 05:21:33)
·C语言指针的定义和使 (2025-12-26 05:21:31)
·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)