Loading...
Searching...
No Matches
staticInterface.h
Go to the documentation of this file.
1//
2// Copyright 2016 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_PLUG_STATIC_INTERFACE_H
8#define PXR_BASE_PLUG_STATIC_INTERFACE_H
9
11
12#include "pxr/pxr.h"
13#include "pxr/base/plug/api.h"
14
15#include <atomic>
16#include <type_traits>
17#include <typeinfo>
18
19PXR_NAMESPACE_OPEN_SCOPE
20
21// Base class for common stuff.
22class Plug_StaticInterfaceBase {
23public:
27 bool IsInitialized() const
28 {
29 return _initialized;
30 }
31
32#if !defined(doxygen)
33 typedef void* Plug_StaticInterfaceBase::*UnspecifiedBoolType;
34#endif
35
36protected:
37 PLUG_API
38 void _LoadAndInstantiate(const std::type_info& type) const;
39
40protected:
41 // POD types only!
42 mutable std::atomic<bool> _initialized;
43 mutable void* _ptr;
44};
45
142template <class Interface>
143class PlugStaticInterface : private Plug_StaticInterfaceBase {
144public:
145 static_assert(std::is_abstract<Interface>::value,
146 "Interface type must be abstract.");
147
149
150 using Plug_StaticInterfaceBase::IsInitialized;
151
154 operator UnspecifiedBoolType() const
155 {
156 return _GetPtr() ? &This::_ptr : nullptr;
157 }
158
161 bool operator!() const
162 {
163 return !*this;
164 }
165
168 Interface* Get() const
169 {
170 return _GetPtr();
171 }
172
175 Interface* operator->() const
176 {
177 return _GetPtr();
178 }
179
183 Interface& operator*() const
184 {
185 return *_GetPtr();
186 }
187
188private:
189 Interface* _GetPtr() const
190 {
191 if (!_initialized) {
192 _LoadAndInstantiate(typeid(Interface));
193 }
194
195 // XXX: We must assume _ptr has the right type since we have
196 // no common base class to dynamic_cast<> from.
197 return static_cast<Interface*>(_ptr);
198 }
199};
200
201PXR_NAMESPACE_CLOSE_SCOPE
202
203#endif // PXR_BASE_PLUG_STATIC_INTERFACE_H
Provides access to an interface into a plugin.
Interface * Get() const
Returns the interface pointer, loading the plugin if necessary.
bool operator!() const
Load and instantiate then return false if the interface is valid, true otherwise.
Interface & operator*() const
Returns the interface pointer as a reference, loading the plugin if necessary.
Interface * operator->() const
Returns the interface pointer, loading the plugin if necessary.