Bond
 
Loading...
Searching...
No Matches
value_or_reference.h
1// Copyright (c) Microsoft. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4#pragma once
5
6#include <bond/core/config.h>
7
8#include <boost/core/ref.hpp>
9#include <boost/optional.hpp>
10#include <boost/utility/enable_if.hpp>
11
12#include <functional>
13#include <type_traits>
14
15namespace bond { namespace ext { namespace detail
16{
18 template <typename T>
20 {
21 public:
22 template <typename U = T, typename boost::enable_if<std::is_constructible<T, U&&>>::type* = nullptr>
23 value_or_reference(U&& value = {})
24 : _value{ std::forward<U>(value) },
25 _ref{ *_value }
26 {}
27
28 value_or_reference(std::reference_wrapper<T> ref) BOND_NOEXCEPT
29 : _value{},
30 _ref{ ref.get() }
31 {}
32
33 value_or_reference(boost::reference_wrapper<T> ref) BOND_NOEXCEPT
34 : _value{},
35 _ref{ ref.get() }
36 {}
37
39 : _value{ other._value },
40 _ref{ _value ? std::ref(*_value) : other._ref }
41 {}
42
43 value_or_reference& operator=(const value_or_reference& other)
44 {
45 _value = other._value;
46 _ref = _value ? std::ref(*_value) : other._ref;
47 return *this;
48 }
49
50 T& get() const BOND_NOEXCEPT
51 {
52 return _ref;
53 }
54
55 private:
56 template <typename U>
57 friend class value_or_reference;
58
59 boost::optional<T> _value;
60 std::reference_wrapper<T> _ref;
61 };
62
63
64 template <typename T>
65 class value_or_reference<T&>
66 {
67 public:
68 value_or_reference(T& value) BOND_NOEXCEPT
69 : _ref{ value }
70 {}
71
72 value_or_reference(std::reference_wrapper<T> ref) BOND_NOEXCEPT
73 : value_or_reference{ ref.get() }
74 {}
75
76 value_or_reference(boost::reference_wrapper<T> ref) BOND_NOEXCEPT
77 : value_or_reference{ ref.get() }
78 {}
79
80 T& get() const BOND_NOEXCEPT
81 {
82 return _ref;
83 }
84
85 private:
86 std::reference_wrapper<T> _ref;
87 };
88
89} } } // namespace bond::ext::detail
Helper type that can hold either a value or a reference.
Definition: value_or_reference.h:20
namespace bond
Definition: apply.h:17