Skip to content

Instantly share code, notes, and snippets.

@MaikKlein
Created July 28, 2014 17:33
Show Gist options
  • Save MaikKlein/15bd54eaa0cc779ec63f to your computer and use it in GitHub Desktop.
Save MaikKlein/15bd54eaa0cc779ec63f to your computer and use it in GitHub Desktop.
#include <functional>
#include <iostream>
template<typename T>
class MaybePtr{
T* ptr;
public:
MaybePtr(T* p) : ptr(p) {}
template <typename F,typename R = std::result_of<F(T*)>::type>
R Get(F access,R default_value){
if (ptr != nullptr)
return access(ptr);
else
return default_value;
}
void Access(std::function<void(T*)> access){
if (ptr != nullptr)
access(ptr);
}
};
int main(){
int * iptr = new int;
*iptr = 10;
auto m = MaybePtr<int>(iptr);
auto addOne = [](int* i) -> int {
return *i + 1;
};
auto setTo42 = [](int* i) {
*i = 42;
};
m.Access(setTo42);
int r = m.Get(addOne, 0);
std::cout << r;
int i;
std::cin >> i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment