Advertisement
tinyevil

Untitled

Nov 22nd, 2018
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. struct prefix{
  2.     enum tag{
  3.         t1,
  4.         t2
  5.     } t;
  6.     int some_shared_data;
  7.     int more_shared_data;
  8. }
  9.  
  10. struct t1{
  11.     prefix p;
  12.     int t1specific;
  13.    
  14.     @proxy p;
  15. }
  16.  
  17. struct t2{
  18.     prefix p;
  19.     string t2specific;
  20.    
  21.     @proxy p;
  22. }
  23.  
  24. @patternmatching(prefix){
  25.     function t1pattern(prefix* p, t1** out): bool{
  26.         if ( p->t == prefix::tag::t1 ){
  27.             *out = (t1*)p;
  28.             return true;
  29.         }
  30.         return false;
  31.     }
  32.    
  33.     function t2pattern(prefix* p, t2** out): bool{
  34.         if ( p->t == prefix::tag::t2 ){
  35.             *out = (t2*)p;
  36.             return true;
  37.         }
  38.         return false;
  39.     }
  40. }
  41.  
  42.  
  43. void use(prefix* p){
  44.     switch ( p ){
  45.     case t1pattern(concrete):
  46.         // concrete is of type t1*
  47.     case t2pattern(concrete):
  48.         // concrete is of type t2*
  49.     // enforces that you covered all the cases (or requires a default one)
  50.     }
  51.     // unfolds into
  52.     {
  53.         t1* concrete;
  54.         if ( t1pattern(p, &concrete) ){
  55.             // concrete is of type t1*
  56.         }else{
  57.             t2* concrete;
  58.             if ( t2pattern(p, &concrete) ){
  59.                 // concrete is of type t2*
  60.             }else{
  61.                 unreachable!();
  62.             }
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement