SHARE
TWEET

Untitled

a guest May 27th, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <variant>
  3.  
  4. class Foo{
  5.     struct TagA {};
  6.     struct TagB {};
  7.    
  8.     struct A1 {
  9.         int i;
  10.         int j;
  11.     };
  12.     struct A2 {
  13.         int k;
  14.     };
  15.  
  16.     struct A {
  17.         A1 a1;
  18.         A2 a2;
  19.     };
  20.    
  21.     struct B {
  22.         int z;
  23.     };
  24.    
  25.     template< typename... Ts >
  26.     constexpr Foo(TagA, Ts&&... ts) : var{A{std::forward<Ts>(ts)...}} {
  27.     }
  28.    
  29.     template< typename... Ts >
  30.     constexpr Foo(TagB, Ts&&... ts) : var{B{std::forward<Ts>(ts)...}} {
  31.     }
  32. public:
  33.     template< bool x, typename... Ts >
  34.     static constexpr Foo create(Ts&&... ts) {
  35.         if constexpr (x) {
  36.             return Foo{TagA{}, std::forward<Ts>(ts)...};
  37.         } else {
  38.             return Foo{TagB{}, std::forward<Ts>(ts)...};
  39.         }
  40.     }
  41.  
  42.     std::variant< A, B > var;
  43. };
  44.  
  45.  
  46. int main()
  47. {
  48.     std::cout << "main begin" << std::endl;
  49.    
  50.     constexpr auto foo1 = Foo::create<true>(1, 2, 4);
  51.     constexpr auto foo2 = Foo::create<false>(10);
  52.    
  53.     static_assert(foo1.var.index() == 0);
  54.     static_assert(foo2.var.index() == 1);
  55.    
  56.     static_assert(std::get<0>(foo1.var).a1.i == 1);
  57.     static_assert(std::get<0>(foo1.var).a1.j == 2);
  58.     static_assert(std::get<0>(foo1.var).a2.k == 4);
  59.    
  60.     static_assert(std::get<1>(foo2.var).z == 10);
  61.    
  62.     return 0;
  63. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top