Skip to content

Instantly share code, notes, and snippets.

@cjxgm
Created December 23, 2014 04:05
Show Gist options
  • Save cjxgm/78e5e47be97ec245ec8d to your computer and use it in GitHub Desktop.
Save cjxgm/78e5e47be97ec245ec8d to your computer and use it in GitHub Desktop.
shared_pod
#include <iostream>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
#include <type_traits>
#include <memory>
namespace tue
{
struct default_tag {};
template <class T, class TAG=default_tag>
struct shared_pod
{
static_assert(std::is_pod<T>{}, "T must be a POD");
static_assert(!std::is_same<T, bool>{}, "T can not be bool");
using element_type = T;
using tag = TAG;
private:
using sptr = std::shared_ptr<element_type>;
sptr element;
public:
shared_pod() = default;
template <class DELETER>
shared_pod(element_type e, DELETER d)
: element {
new element_type(e),
[d = std::move(d)](auto x) { d(*x); delete x; }
}
{}
operator bool () const { return element; }
operator element_type () const { return *element; }
};
}
int main()
{
auto deleter = [](auto x) { cout << x << endl; };
tue::shared_pod<int> x;
tue::shared_pod<int> y;
x = {3, deleter};
x = {4, deleter};
y = x;
x = {5, deleter};
cout << ">> " << int(x) << endl;
cout << "----" << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment