flyweight.hpp
Loading...
Searching...
No Matches
Classes | Functions
flyweight.hpp File Reference
#include <functional>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>

Go to the source code of this file.

Classes

struct  flyweight::default_creator< T, Args >
 
struct  flyweight::default_deleter< T >
 
struct  flyweight::autorelease_value< T, Flyweight, ArgTuple >
 Value wrapper that releases it back to the owning flyweight upon destruction. More...
 
class  flyweight::flyweight< T, Args >
 
class  flyweight::flyweight_refcounted< T, Args >
 

Functions

template<typename Fn , typename... Args>
auto flyweight::detail::apply (Fn &&f, std::tuple< Args... > &&t)
 

Detailed Description

Single header with a templated implementation of the Flyweight design pattern

Example of asset management using flyweight objects:

#include "flyweight.hpp"
// 1. Declare your flyweight instance.
// The first template type is the value type.
// The rest are argument types used to create values.
// In this example, we're defining a resource manager for images.
// (optional) Pass a creator functor that will be called to create values.
[](const std::string& image_name) {
return LoadImage(image_name);
},
// (optional) Pass a deleter functor that will be called when values are released.
[](Image& image) {
UnloadImage(image);
},
};
// 2. Get values from the flyweight.
// The first time the value will be created.
Image& image1 = my_image_flyweight.get("image1");
assert(my_image_flyweight.is_loaded("image1"));
// Subsequent gets will return the same reference to the same value.
Image& also_image1 = my_image_flyweight.get("image1");
assert(&image1 == &also_image1);
// 3. When you don't need values anymore, release them to the flyweight again.
my_image_flyweight.release("image1");
assert(!my_image_flyweight.is_loaded("image1"));
// Releasing a value that is not loaded is a harmless no-op.
my_image_flyweight.release("image that's not loaded");
// 4. (optional) Use RAII to automatically release a value by getting it with `get_autorelease`.
{
auto autoreleased_image1 = my_image_flyweight.get_autorelease("image1");
assert(my_image_flyweight.is_loaded("image1"));
// Autoreleased values are simple wrappers to the original value reference.
Image& image1 = autoreleased_image1;
}
// At this point "image1" was automatically released.
assert(!my_image_flyweight.is_loaded("image1"));
Definition: flyweight.hpp:272