vsg: include/vsg/io/ObjectFactory.h Source File

vsg 1.1.10 VulkanSceneGraph library |

Loading...
Searching...
No Matches
ObjectFactory.h
1#pragma once
2
3/* <editor-fold desc="MIT License">
4
5Copyright(c) 2018 Robert Osfield
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
9The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
11THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12
13</editor-fold> */
14
15#include <vsg/core/Object.h>
16#include <vsg/core/type_name.h>
17
18#include <functional>
19#include <map>
20
21namespace vsg
22{
23
26 class VSG_DECLSPEC ObjectFactory : public vsg::Object
27 {
28 public:
29 ObjectFactory();
30
31 virtual vsg::ref_ptr<vsg::Object> create(const std::string& className);
32
33 using CreateFunction = std::function<vsg::ref_ptr<vsg::Object>()>;
34 using CreateMap = std::map<std::string, CreateFunction>;
35
36 CreateMap& getCreateMap() { return _createMap; }
37 const CreateMap& getCreateMap() const { return _createMap; }
38
39 template<class T>
40 void add()
41 {
42 _createMap[type_name<T>()] = []() { return T::create(); };
43 }
44
46 static ref_ptr<ObjectFactory>& instance();
47
48 protected:
49 virtual ~ObjectFactory();
50
51 CreateMap _createMap;
52 };
53
54 // Helper template class for registering the ability to create an Object of specified T on demand.
55 template<class T>
56 struct RegisterWithObjectFactoryProxy
57 {
58 RegisterWithObjectFactoryProxy()
59 {
60 ObjectFactory::instance()->add<T>();
61 }
62 };
63
64} // namespace vsg
vsg::ObjectFactory::instance
static ref_ptr< ObjectFactory > & instance()
return the ObjectFactory singleton instance
vsg::Object
Definition Object.h:60
vsg::ref_ptr
Definition ref_ptr.h:22