Skip to content

Instantly share code, notes, and snippets.

@maluramichael
Created November 13, 2014 14:54
Show Gist options
  • Save maluramichael/55bd1cc160676cdd76e5 to your computer and use it in GitHub Desktop.
Save maluramichael/55bd1cc160676cdd76e5 to your computer and use it in GitHub Desktop.
Make Resource
#include <iostream>
#include <bitset>
#include <vector>
#include <map>
#include <algorithm>
#include <memory>
template<typename Creator, typename Destructor, typename... Arguments>
auto make_resource(Creator c, Destructor d, Arguments&&... args){
auto r = c(std::forward<Arguments>(args)...);
if (!r) {throw std::runtime_error{"Unable to create resource"};}
typedef typename std::decay<decltype(*r)>::type ResourceType;
return std::unique_ptr<ResourceType, void(*)(ResourceType*)>(r,d);
}
class Foo {
private:
int _a;
public:
Foo(int a){
std::cout << "constructor Foo\n";
_a = a;
}
~Foo(){
std::cout << "destructor Foo\n";
}
int getA(){
return _a;
}
};
Foo *createFoo(int a) {
std::cout << "createFoo\n";
return new Foo(a);
}
void deleteFoo(Foo* foo){
std::cout << "deleteFoo\n";
delete foo;
}
int main() {
auto foo = make_resource(createFoo, deleteFoo, 20);
std::cout << foo->getA() << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment