1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// UNSUPPORTED: c++03, c++11, c++14
10
11// <variant>
12
13// template <class ...Types> class variant;
14
15// constexpr variant() noexcept(see below);
16
17#include <cassert>
18#include <type_traits>
19#include <variant>
20
21#include "test_macros.h"
22#include "variant_test_helpers.h"
23
24struct NonDefaultConstructible {
25 constexpr NonDefaultConstructible(int) {}
26};
27
28struct NotNoexcept {
29 NotNoexcept() noexcept(false) {}
30};
31
32#ifndef TEST_HAS_NO_EXCEPTIONS
33struct DefaultCtorThrows {
34 DefaultCtorThrows() { throw 42; }
35};
36#endif
37
38void test_default_ctor_sfinae() {
39 {
40 using V = std::variant<std::monostate, int>;
41 static_assert(std::is_default_constructible<V>::value, "");
42 }
43 {
44 using V = std::variant<NonDefaultConstructible, int>;
45 static_assert(!std::is_default_constructible<V>::value, "");
46 }
47}
48
49void test_default_ctor_noexcept() {
50 {
51 using V = std::variant<int>;
52 static_assert(std::is_nothrow_default_constructible<V>::value, "");
53 }
54 {
55 using V = std::variant<NotNoexcept>;
56 static_assert(!std::is_nothrow_default_constructible<V>::value, "");
57 }
58}
59
60void test_default_ctor_throws() {
61#ifndef TEST_HAS_NO_EXCEPTIONS
62 using V = std::variant<DefaultCtorThrows, int>;
63 try {
64 V v;
65 assert(false);
66 } catch (const int &ex) {
67 assert(ex == 42);
68 } catch (...) {
69 assert(false);
70 }
71#endif
72}
73
74void test_default_ctor_basic() {
75 {
76 std::variant<int> v;
77 assert(v.index() == 0);
78 assert(std::get<0>(v) == 0);
79 }
80 {
81 std::variant<int, long> v;
82 assert(v.index() == 0);
83 assert(std::get<0>(v) == 0);
84 }
85 {
86 std::variant<int, NonDefaultConstructible> v;
87 assert(v.index() == 0);
88 assert(std::get<0>(v) == 0);
89 }
90 {
91 using V = std::variant<int, long>;
92 constexpr V v;
93 static_assert(v.index() == 0, "");
94 static_assert(std::get<0>(v: v) == 0, "");
95 }
96 {
97 using V = std::variant<int, long>;
98 constexpr V v;
99 static_assert(v.index() == 0, "");
100 static_assert(std::get<0>(v: v) == 0, "");
101 }
102 {
103 using V = std::variant<int, NonDefaultConstructible>;
104 constexpr V v;
105 static_assert(v.index() == 0, "");
106 static_assert(std::get<0>(v: v) == 0, "");
107 }
108}
109
110int main(int, char**) {
111 test_default_ctor_basic();
112 test_default_ctor_sfinae();
113 test_default_ctor_noexcept();
114 test_default_ctor_throws();
115
116 return 0;
117}
118

source code of libcxx/test/std/utilities/variant/variant.variant/variant.ctor/default.pass.cpp