Advertisement
Guest User

Untitled

a guest
Aug 26th, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. fn Iterator(comptime SELF: type, comptime Item: type) type {
  2.     return struct {
  3.         pub fn REQUIRE_next(self: *SELF) ?Item {
  4.             return undefined;
  5.         }
  6.     };
  7. }
  8.  
  9. fn AsRef(comptime SELF: type, comptime Target: type) type {
  10.     return struct {
  11.         pub fn REQUIRE_as_ref(self: *const SELF) *const Target {
  12.             return undefined;
  13.         }
  14.     };
  15. }
  16.  
  17. fn require(comptime TRAIT: var, comptime CHECK: var) bool {
  18.     const fn_names_to_check = @typeInfo(TRAIT).Struct;
  19.    
  20.     const to_check_type_info = @typeInfo(CHECK).Struct;
  21.    
  22.     inline for(fn_names_to_check.defs) |name| {
  23.         inline for (to_check_type_info.defs) |def| {
  24.             if(mem.eql(u8, name.name[8..], def.name)) {
  25.                 if (mem.eql(u8, @typeName(name.data.Fn.fn_type), @typeName(def.data.Fn.fn_type))) {
  26.                     return true;
  27.                 }
  28.             }
  29.         }
  30.     }
  31.  
  32.     return false;
  33. }
  34.  
  35. const thingy = struct {
  36.     data: usize,
  37.     pub fn next(self: *this) ?u32 {
  38.         return 10;
  39.     }
  40.  
  41.     pub fn as_ref(self: *const this) *const usize {
  42.         return &(self.data);
  43.     }
  44. };
  45.  
  46. pub fn test_asref(comptime T: type, item: T) void {
  47.     comptime {
  48.         if (!require(AsRef(T, usize), T)) {
  49.             @compileError("T needs to implement AsRef");
  50.         }
  51.     }
  52.  
  53.     std.debug.warn("data: {}\n", item.as_ref().* );
  54. }
  55.  
  56. pub fn main() void {
  57.  
  58.     var thing = thingy { .data = 10 };
  59.  
  60.     test_asref(thingy, thing);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement