Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Last active June 19, 2016 11:59
Show Gist options
  • Save pyrtsa/534080c5c8d342e66a19 to your computer and use it in GitHub Desktop.
Save pyrtsa/534080c5c8d342e66a19 to your computer and use it in GitHub Desktop.
WTF C++14
// Not quite as bad as https://twitter.com/ivansafrin/status/457248037157740544 but still hairy.
#include <memory>
#include <type_traits>
#include <iostream>
template <typename Creator, typename Destructor, typename... Arguments>
auto make_resource(Creator c, Destructor d, Arguments &&... args) {
using value_t = typename std::decay<decltype(*c(std::forward<Arguments>(args)...))>::type;
using ptr_t = std::unique_ptr<value_t, void (*)(value_t *)>;
return ptr_t(c(std::forward<Arguments>(args)...), d);
}
struct res { int i; };
res *make_res(int i) {
std::cout << "res{" << i << "}" << std::endl;
return new res{i};
}
void delete_res(res * p) {
std::cout << "~res{" << p->i << "}" << std::endl;
delete p;
}
int main() {
auto f = make_resource(make_res, delete_res, 123);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment