File: abg-cxx-compat.h

package info (click to toggle)
libabigail 2.9-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,021,752 kB
  • sloc: xml: 572,663; cpp: 110,945; sh: 11,868; ansic: 4,329; makefile: 3,486; python: 1,684; ada: 62
file content (117 lines) | stat: -rw-r--r-- 2,147 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// -*- Mode: C++ -*-
//
// Copyright (C) 2019-2025 Google, Inc.

/// @file

#ifndef __ABG_CXX_COMPAT_H
#define __ABG_CXX_COMPAT_H

// C++17 support (via custom implementations if compiled with earlier standard)

#if __cplusplus >= 201703L

#include <optional>

#else

#include <stdexcept> // for throwing std::runtime_error("bad_optional_access")

#endif

namespace abg_compat {

#if __cplusplus >= 201703L

using std::optional;

#else

// <optional>

/// Simplified implementation of std::optional just enough to be used as a
/// replacement for our purposes and when compiling with pre C++17.
///
/// The implementation intentionally does not support a whole lot of features
/// to minimize the maintenance effort with this.
template <typename T> class optional
{
  bool has_value_;
  T    value_;

public:
  optional() : has_value_(false), value_() {}
  optional(const T& value) : has_value_(true), value_(value) {}

  bool
  has_value() const noexcept
  {
    return has_value_;
  }

  const T&
  value() const
  {
    if (!has_value_)
      throw std::runtime_error("bad_optional_access");
    return value_;
  }

  const T
  value_or(const T& default_value) const
  {
    if (!has_value_)
      return default_value;
    return value_;
  }

  const T&
  operator*() const& noexcept
  { return value_; }

  T&
  operator*() & noexcept
  { return value_; }

  const T*
  operator->() const noexcept
  { return &value_; }

  T*
  operator->() noexcept
  { return &value_; }

  optional&
  operator=(const T& value)
  {
    has_value_ = true;
    value_ = value;
    return *this;
  }

  explicit operator bool() const noexcept { return has_value(); }
};

template <typename T, typename U>
bool
operator==(const optional<T>& lhs, const optional<U>& rhs)
{
  if (!lhs.has_value() && !rhs.has_value())
    return true;
  if (!lhs.has_value() || !rhs.has_value())
    return false;
  return lhs.value() == rhs.value();
}

template <typename T, typename U>
bool
operator!=(const optional<T>& lhs, const optional<U>& rhs)
{
  return !(lhs == rhs);
}

#endif
}

#endif  // __ABG_CXX_COMPAT_H