I am trying to write a resource shell compatible with RAII, and I am fixated on how to form the semantics of the template parameters.
For example, I can write a function to delete my resource:
void int_cleaner(int val) {
std::cout << "Value of " << val << " has been cleaned up." << std::endl;
}
Or I could write this as a Functor:
struct int_deleter {
void operator()(int val) const {
std::cout << "Value of " << val << " has been cleaned up." << std::endl;
}
};
But here, where I am stuck: if I want to pass this into my resource shell, I need to change the way the template parameter is defined.
If I write resourceas follows:
template<typename T, typename Deleter>
class resource {
};
This works great with a functor, but not with the function itself.
int main() {
resource<int, int_deleter> res;
return 0;
}
And vice versa, if I write the template parameters as follows:
template<typename T>
using deleter_t = void(*)(T);
template<typename T, deleter_t<T> Deleter>
class resource {
};
int main() {
resource<int, int_cleaner> res2;
return 0;
}
Now I can write both versions of the code, but there are two reasons why I do not want to do this:
resource, , .- , ,
void cleaner(T const&), void(*)(T). , T, T&, T const& T&&.
, , , ?
template<typename T>
using deleter_t = void(*)(T);
template<typename T, deleter_t<T> Deleter>
class resource {
~resource() {Deleter(val);}
};
template<typename T, typename Deleter>
class resource {
~resource() {Deleter{}(val);}
};