I was trying to implement an std::unique_ptr
factory that I could use like this:
auto fd = my_make_unique<fclose>(fopen("filename", "r"));
I.e., 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 both solutuions would require me to pass the type of &fclose
before fclose
itself as template argument:
auto fd = my_make_unique<decltype(&fclose), fclose>(fopen("filename", "r"));
Is it possible to get rid of decltype(&fclose)
template argument in C++11? What about in C++14?
EDIT: Why this question is not a duplicate of RAII and smart pointers in C++: referenced question is about general RAII techniques in C++, and one of the answers estates that std::unique_ptr
can be used for this purpose. I am already familiar with RAII pattern and how std::unique_ptr
is a solution, but I am concerned with present question on how to build an easier to use abstraction to this frequent case I encounter when interacting with C libraries.