I tried to implement a std::unique_ptrfactory that I could use like this:
auto fd = my_make_unique<fclose>(fopen("filename", "r"));
Ie, pass the deleter function as a template argument.
My best attempt in C ++ 11 was:
template<typename D, D deleter, typename P>
struct Deleter {
void operator()(P* ptr) {
deleter(ptr);
}
};
template<typename D, D deleter, typename P>
std::unique_ptr<P, Deleter<D, deleter, P>> my_make_unique(P* ptr)
{
return std::unique_ptr<P, Deleter<D, deleter, P>>(ptr);
}
In C ++ 14 it is much cleaner:
template<typename D, D deleter, typename P>
auto my_make_unique(P* ptr)
{
struct Deleter {
void operator()(P* ptr) {
deleter(ptr);
}
};
return std::unique_ptr<P, Deleter>(ptr);
}
But for both solutions, you will need to pass the type &fcloseto fcloseas a template argument:
auto fd = my_make_unique<decltype(&fclose), fclose>(fopen("filename", "r"));
Is it possible to get rid of a template argument decltype(&fclose)in C ++ 11? How about in C ++ 14?
EDIT: RAII ++: RAII ++, - std::unique_ptr . RAII std::unique_ptr , , , C.