Advertisement
Guest User

Untitled

a guest
Feb 28th, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. pub fn hasFieldRec(comptime name: []const u8) TraitFn {
  2.     const Closure = struct {
  3.         pub fn trait(comptime T: type) bool {
  4.  
  5.             const info = @typeInfo(T);
  6.             const fields = switch (info) {
  7.                 builtin.TypeId.Struct => |s| s.fields,
  8.                 builtin.TypeId.Union => |u| u.fields,
  9.                 builtin.TypeId.Enum => |e| e.fields,
  10.                 else => return false,
  11.             };
  12.  
  13.             inline for(fields) |field| {
  14.                 if (mem.eql(u8, field.name, name)) return true;
  15.             }
  16.  
  17.             inline for(fields) |field| {
  18.                 if (hasFieldRec(name)(field.field_type)) return true;
  19.             }
  20.  
  21.             return false;
  22.         }
  23.     };
  24.  
  25.     return Closure.trait;
  26. }
  27.  
  28. test "rec field" {
  29.     const base = struct {
  30.         number: i32,
  31.     };
  32.  
  33.     const nest = struct {
  34.         nesting: base,
  35.     };
  36.  
  37.     std.debug.assert(hasFieldRec("number")(nest));
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement