Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <variant>
- class Foo{
- struct TagA {};
- struct TagB {};
- struct A1 {
- int i;
- int j;
- };
- struct A2 {
- int k;
- };
- struct A {
- A1 a1;
- A2 a2;
- };
- struct B {
- int z;
- };
- template< typename... Ts >
- constexpr Foo(TagA, Ts&&... ts) : var{A{std::forward<Ts>(ts)...}} {
- }
- template< typename... Ts >
- constexpr Foo(TagB, Ts&&... ts) : var{B{std::forward<Ts>(ts)...}} {
- }
- public:
- template< bool x, typename... Ts >
- static constexpr Foo create(Ts&&... ts) {
- if constexpr (x) {
- return Foo{TagA{}, std::forward<Ts>(ts)...};
- } else {
- return Foo{TagB{}, std::forward<Ts>(ts)...};
- }
- }
- std::variant< A, B > var;
- };
- int main()
- {
- std::cout << "main begin" << std::endl;
- constexpr auto foo1 = Foo::create<true>(1, 2, 4);
- constexpr auto foo2 = Foo::create<false>(10);
- static_assert(foo1.var.index() == 0);
- static_assert(foo2.var.index() == 1);
- static_assert(std::get<0>(foo1.var).a1.i == 1);
- static_assert(std::get<0>(foo1.var).a1.j == 2);
- static_assert(std::get<0>(foo1.var).a2.k == 4);
- static_assert(std::get<1>(foo2.var).z == 10);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement