Created
July 28, 2014 17:33
-
-
Save MaikKlein/15bd54eaa0cc779ec63f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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