Created
April 2, 2014 18:05
-
-
Save tclamb/9939650 to your computer and use it in GitHub Desktop.
DeadMG's `unique_ptr` wrapper for opaque types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <memory> | |
int open() { return 1; } | |
void close(int) {} | |
template<typename T, typename Deleter, Deleter d, T null_value = T{}> | |
struct value_deleter | |
{ | |
struct wrapper | |
{ | |
T value; | |
wrapper() : value{null_value} {} | |
wrapper(T t) : value{t} {} | |
wrapper(std::nullptr_t) : value{null_value} {} | |
bool operator==(std::nullptr_t) { return value == null_value; } | |
bool operator!=(std::nullptr_t) { return value != null_value; } | |
T operator*() { return value; } | |
}; | |
using pointer = wrapper; | |
void operator()(wrapper w) { | |
if (w.value != null_value) | |
d(w.value); | |
} | |
}; | |
int main() { | |
std::unique_ptr<int, value_deleter<int, decltype(&close), &close>> ptr(open()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment