Hi,
unique_ptr can emulate unique_resource:
template
class unique
{
using T = decltype(nullvalue);
struct generic_delete
{
class pointer
{
T t;
public:
pointer(T t) : t(t) {}
pointer(std::nullptr_t = nullptr) : t(nullvalue) { }
explicit operator bool() { return t != nullvalue; }
friend bool operator ==(pointer lhs, pointer rhs) {
return lhs.t == rhs.t; }
friend bool operator !=(pointer lhs, pointer rhs) {
return lhs.t != rhs.t; }
operator T() { return t; }
};
void operator()(T p)
{
delete_(p);
}
};
public:
using type = std::unique_ptr;
};
int main()
{
using unique_fd = unique<-1, close>::type;
static_assert(sizeof(unique_fd) == sizeof(int), "bloated unique_fd");
unique_fd fd1(open("fd.txt", O_WRONLY | O_CREAT | O_TRUNC));
write(fd1.get(), "hello\n", 6);
}
The std papers say
While std::unique_ptr can be tweaked by using a custom deleter
type to almost a
perfect handler for resources, it is awkward to use for handle types
that are not pointers.
But what's the awkwardness?
Kind regards,
Bruno