78 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9// <optional>10// UNSUPPORTED: c++03, c++11, c++1411 12// template<class T>13// optional(T) -> optional<T>;14 15#include <cassert>16#include <optional>17 18#include "test_macros.h"19 20struct A {};21 22int main(int, char**) {23 // Test the explicit deduction guides24 {25 // optional(T)26 std::optional opt(5);27 ASSERT_SAME_TYPE(decltype(opt), std::optional<int>);28 assert(static_cast<bool>(opt));29 assert(*opt == 5);30 }31 32 {33 // optional(T)34 std::optional opt(A{});35 ASSERT_SAME_TYPE(decltype(opt), std::optional<A>);36 assert(static_cast<bool>(opt));37 }38 39 {40 // optional(const T&);41 const int& source = 5;42 std::optional opt(source);43 ASSERT_SAME_TYPE(decltype(opt), std::optional<int>);44 assert(static_cast<bool>(opt));45 assert(*opt == 5);46 }47 48 {49 // optional(T*);50 const int* source = nullptr;51 std::optional opt(source);52 ASSERT_SAME_TYPE(decltype(opt), std::optional<const int*>);53 assert(static_cast<bool>(opt));54 assert(*opt == nullptr);55 }56 57 {58 // optional(T[]);59 int source[] = {1, 2, 3};60 std::optional opt(source);61 ASSERT_SAME_TYPE(decltype(opt), std::optional<int*>);62 assert(static_cast<bool>(opt));63 assert((*opt)[0] == 1);64 }65 66 // Test the implicit deduction guides67 {68 // optional(optional);69 std::optional<char> source('A');70 std::optional opt(source);71 ASSERT_SAME_TYPE(decltype(opt), std::optional<char>);72 assert(static_cast<bool>(opt) == static_cast<bool>(source));73 assert(*opt == *source);74 }75 76 return 0;77}78