Skip to content

Instantly share code, notes, and snippets.

@kris7t
Created August 1, 2014 14:32
Show Gist options
  • Save kris7t/e60a3320795609bfa641 to your computer and use it in GitHub Desktop.
Save kris7t/e60a3320795609bfa641 to your computer and use it in GitHub Desktop.
#ifndef SUCCESS_SHAREABLE_H_
#define SUCCESS_SHAREABLE_H_
#include <memory>
#include <utility>
namespace success {
template <typename T>
class Shareable : private std::shared_ptr<T> {
public:
template <typename... Args>
static Shareable Make(Args &&... args) {
return Shareable(std::make_shared<T>(std::forward<Args>(args)...));
}
Shareable() : std::shared_ptr<T>() { }
Shareable(T *p) : std::shared_ptr<T>(p) { }
Shareable(Shareable &other)
: std::shared_ptr<T>(std::make_shared<T>(*other)) {
}
Shareable(Shareable &&other) = default;
Shareable &operator=(const Shareable &other) {
if (*other != this) {
std::shared_ptr<T>::operator=(std::make_shared<T>(*other));
}
return *this;
}
Shareable &operator=(Shareable &&other) = default;
using std::shared_ptr<T>::get;
using std::shared_ptr<T>::operator*;
using std::shared_ptr<T>::operator->;
using std::shared_ptr<T>::operator bool;
std::shared_ptr<T> share() const {
return *this;
}
private:
Shareable(std::shared_ptr<T> shared)
: std::shared_ptr<T>(std::move(shared)) {
}
};
template <typename T, typename... Args>
Shareable<T> MakeShareable(Args &&... args) {
return Shareable<T>::Make(std::forward<Args>(args)...);
}
#define SHAREABLE_CONTAINER2(NAME, TYPE) \
template <typename T> \
using Shared ## NAME = std::shared_ptr<TYPE<T> >; \
template <typename T> \
using ConstShared ## NAME = std::shared_ptr<const TYPE<T> >; \
template <typename T> \
using Shareable ## NAME = Shareable<TYPE<T> >; \
template <typname T, typename... Args> \
Shared ## NAME<T> MakeShared ## NAME(Args &&... args) { \
return std::make_shared<TYPE<T> >(std::forward<Args>(args)...); \
} \
template <typname T, typename... Args> \
Shareable ## NAME<T> MakeShareable ## NAME(Args &&... args) { \
return MakeShareable<TYPE<T> >(std::forward<Args>(args)...); \
}
#define SHAREABLE_CONTAINER(NAME) SHAREABLE_CONTAINER2(NAME, NAME)
SHAREABLE_CONTAINER2(Vector, std::vector)
} // namespace success
#endif // SUCCESS_SHAREABLE_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment