Advertisement
Guest User

Untitled

a guest
Feb 28th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 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.                 if (hasFieldRec(name)(field.field_type)) return true;
  16.             }
  17.  
  18.             return false;
  19.         }
  20.     };
  21.  
  22.     return Closure.trait;
  23. }
  24.  
  25. test "rec field" {
  26.     const base = struct {
  27.         number: i32,
  28.     };
  29.  
  30.     const nest = struct {
  31.         nesting: base,
  32.     };
  33.  
  34.     const doublenest = struct {
  35.         doublenested: nest,
  36.     };
  37.  
  38.     const tripplenest = union(enum) {
  39.         tnest: doublenest,
  40.         x: i32,
  41.     };
  42.    
  43.     // this should be true, base has a `number` field.
  44.     comptime debug.assert(hasFieldRec("number")(tripplenest));
  45.  
  46.     // oopsy, we made a typo. should be false.
  47.     comptime debug.assert(!hasFieldRec("numberr")(tripplenest));
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement