OSVR-Core
Finally.h
Go to the documentation of this file.
1 
20 // Copyright 2016 Sensics, Inc.
21 //
22 // Licensed under the Apache License, Version 2.0 (the "License");
23 // you may not use this file except in compliance with the License.
24 // You may obtain a copy of the License at
25 //
26 // http://www.apache.org/licenses/LICENSE-2.0
27 //
28 // Unless required by applicable law or agreed to in writing, software
29 // distributed under the License is distributed on an "AS IS" BASIS,
30 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 // See the License for the specific language governing permissions and
32 // limitations under the License.
33 
34 #ifndef INCLUDED_Finally_h_GUID_B9F9A283_5381_41A5_3D60_CEF0F8BA8606
35 #define INCLUDED_Finally_h_GUID_B9F9A283_5381_41A5_3D60_CEF0F8BA8606
36 
37 // Internal Includes
38 // - none
39 
40 // Library/third-party includes
41 // - none
42 
43 // Standard includes
44 #include <utility>
45 
46 namespace osvr {
47 namespace util {
54  template <typename F> class FinalTask {
55  public:
57  explicit FinalTask(F f) : f_(std::move(f)) {}
59  FinalTask(FinalTask &&other) : f_(std::move(other.f_)), do_(other.do_) {
60  other.cancel();
61  }
63  FinalTask(FinalTask const &) = delete;
65  FinalTask &operator=(FinalTask const &) = delete;
68  if (do_) {
69  f_();
70  }
71  }
73  void cancel() { do_ = false; }
74 
75  private:
77  F f_;
79  bool do_ = true;
80  };
81 
87  template <typename F> inline FinalTask<F> finally(F &&f) {
89  return FinalTask<F>(std::forward<F>(f));
90  }
91 
93  template <typename F> inline FinalTask<F> finally(F const &f) {
94  // Added this overload because GSL had it and GSL is supposed to be best
95  // practices guidelines...
96  return FinalTask<F>(f);
97  }
98 
99 } // namespace util
100 } // namespace osvr
101 
102 #endif // INCLUDED_Finally_h_GUID_B9F9A283_5381_41A5_3D60_CEF0F8BA8606
Definition: RunLoopManager.h:42
The main namespace for all C++ elements of the framework, internal and external.
Definition: namespace_osvr.dox:3
Definition: TypeSafeIdHash.h:44
Allows you to run a callable something at the end of a scope.
Definition: Finally.h:54
FinalTask & operator=(FinalTask const &)=delete
non-assignable
void cancel()
Cancel causes us to not do our final task on destruction.
Definition: Finally.h:73
FinalTask(F f)
Explicit constructor from something callable.
Definition: Finally.h:57
FinalTask(FinalTask &&other)
Move constructor - cancels the moved-from task.
Definition: Finally.h:59
~FinalTask()
Destructor - if we haven&#39;t been cancelled, do our callable thing.
Definition: Finally.h:67