Easy Navigation
Loading...
Searching...
No Matches
Singleton.hpp
Go to the documentation of this file.
1// Copyright 2025 Intelligent Robotics Lab
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15
16#ifndef EASYNAV_COMMON__SINGLETON_H_
17#define EASYNAV_COMMON__SINGLETON_H_
18
19#include <memory>
20#include <mutex>
21#include <utility>
22
23namespace easynav
24{
25
26template<class C>
28{
29public:
30 template<typename ... Args>
31 static C * getInstance(Args &&... args)
32 {
33 std::call_once(init_flag_, [&]() {
34 instance_ = std::make_unique<C>(std::forward<Args>(args)...);
35 });
36 return instance_.get();
37 }
38
39 static void removeInstance()
40 {
41 instance_.reset();
42 init_flag_ = std::once_flag();
43 }
44
45 template<typename ... Args>
46 static C & get(Args &&... args)
47 {
48 getInstance(std::forward<Args>(args)...);
49 return *instance_;
50 }
51
52protected:
53 Singleton() = default;
54 ~Singleton() = default;
55
56 Singleton(const Singleton &) = delete;
57 Singleton & operator=(const Singleton &) = delete;
58
59private:
60 static std::unique_ptr<C> instance_;
61 static std::once_flag init_flag_;
62};
63
64template<class C>
65std::unique_ptr<C> Singleton<C>::instance_ = nullptr;
66
67template<class C>
68std::once_flag Singleton<C>::init_flag_;
69
70#define SINGLETON_DEFINITIONS(ClassName) \
71public: \
72 static ClassName * getInstance() \
73 { \
74 return ::easynav::Singleton<ClassName>::getInstance(); \
75 } \
76 template<typename ... Args> \
77 static ClassName * getInstance(Args && ... args) \
78 { \
79 return ::easynav::Singleton<ClassName>::getInstance( \
80 std::forward<Args>(args)...); \
81 }
82
83} // namespace easynav
84
85#endif // EASYNAV_COMMON__SINGLETON_H_
static C & get(Args &&... args)
Definition Singleton.hpp:46
Singleton(const Singleton &)=delete
static void removeInstance()
Definition Singleton.hpp:39
Singleton & operator=(const Singleton &)=delete
~Singleton()=default
static C * getInstance(Args &&... args)
Definition Singleton.hpp:31
Definition CircularBuffer.hpp:23