WPILibC++ 2027.0.0-alpha-4
Loading...
Searching...
No Matches
Types.hpp
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7#include "wpi/hal/Types.h"
8
9namespace wpi::hal {
10/**
11 * A move-only C++ wrapper around a HAL handle.
12 * Will free the handle if FreeFunction is provided
13 */
14template <typename CType, void (*FreeFunction)(CType) = nullptr,
15 int32_t CInvalid = HAL_kInvalidHandle>
16class Handle {
17 public:
18 Handle() = default;
19 /*implicit*/ Handle(CType val) : m_handle(val) {} // NOLINT
20
21 Handle(const Handle&) = delete;
22 Handle& operator=(const Handle&) = delete;
23
24 Handle(Handle&& rhs) : m_handle(rhs.m_handle) { rhs.m_handle = CInvalid; }
25
27 if (this != &rhs) {
28// FIXME: GCC gives the false positive "the address of <GetDefault> will never
29// be NULL" because it doesn't realize the default template parameter can make
30// GetDefault nullptr. Fixed in GCC 13.
31// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94554
32// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105885
33#if __GNUC__
34#pragma GCC diagnostic push
35#pragma GCC diagnostic ignored "-Waddress"
36#endif // __GNUC__
37 if constexpr (FreeFunction != nullptr) {
38#if __GNUC__
39#pragma GCC diagnostic pop
40#endif // __GNUC__
41 if (m_handle != CInvalid) {
42 FreeFunction(m_handle);
43 }
44 }
45 }
46 m_handle = rhs.m_handle;
47 rhs.m_handle = CInvalid;
48 return *this;
49 }
50
52// FIXME: GCC gives the false positive "the address of <GetDefault> will never
53// be NULL" because it doesn't realize the default template parameter can make
54// GetDefault nullptr. Fixed in GCC 13.
55// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94554
56// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105885
57#if __GNUC__
58#pragma GCC diagnostic push
59#pragma GCC diagnostic ignored "-Waddress"
60#endif // __GNUC__
61 if constexpr (FreeFunction != nullptr) {
62#if __GNUC__
63#pragma GCC diagnostic pop
64#endif // __GNUC__
65 if (m_handle != CInvalid) {
66 FreeFunction(m_handle);
67 }
68 }
69 }
70
71 operator CType() const { return m_handle; } // NOLINT
72
73 private:
74 CType m_handle = CInvalid;
75};
76
77} // namespace wpi::hal
Handle(const Handle &)=delete
~Handle()
Definition Types.hpp:51
Handle & operator=(const Handle &)=delete
Handle & operator=(Handle &&rhs)
Definition Types.hpp:26
Handle(CType val)
Definition Types.hpp:19
Handle(Handle &&rhs)
Definition Types.hpp:24
Handle()=default
#define HAL_kInvalidHandle
Definition Types.h:15
WPILib Hardware Abstraction Layer (HAL) namespace.
Definition Types.hpp:9