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
32protected:
33 PLUG_API
34 void _LoadAndInstantiate(const std::type_info& type) const;
35
36protected:
37 // POD types only!
38 mutable std::atomic<bool> _initialized;
39 mutable void* _ptr;
40};
41
138template <class Interface>
139class PlugStaticInterface : private Plug_StaticInterfaceBase {
140public:
141 static_assert(std::is_abstract<Interface>::value,
142 "Interface type must be abstract.");
143
145
146 using Plug_StaticInterfaceBase::IsInitialized;
147
150 explicit operator bool() const
151 {
152 return static_cast<bool>(_GetPtr());
153 }
154
157 Interface* Get() const
158 {
159 return _GetPtr();
160 }
161
164 Interface* operator->() const
165 {
166 return _GetPtr();
167 }
168
172 Interface& operator*() const
173 {
174 return *_GetPtr();
175 }
176
177private:
178 Interface* _GetPtr() const
179 {
180 if (!_initialized) {
181 _LoadAndInstantiate(typeid(Interface));
182 }
183
184 // XXX: We must assume _ptr has the right type since we have
185 // no common base class to dynamic_cast<> from.
186 return static_cast<Interface*>(_ptr);
187 }
188};
189
190PXR_NAMESPACE_CLOSE_SCOPE
191
192#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.
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.