Created
December 2, 2015 20:42
-
-
Save hoditohod/52e0d2c981abfc3ce714 to your computer and use it in GitHub Desktop.
Lambda expression holder - void* version
This file contains 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 <iostream> | |
using namespace std; | |
// blank template class | |
template<typename T> | |
class Holder { }; | |
// specialized one with call signature | |
template<typename RetType, typename... ArgsType> | |
class Holder<RetType(ArgsType...)> | |
{ | |
void* lambdaPtr = nullptr; | |
RetType (*caller)(void*, ArgsType...); | |
void (*deleter)(void*); | |
public: | |
RetType call(ArgsType... args) | |
{ | |
return caller(lambdaPtr, args...); | |
} | |
template<typename T> | |
void set(const T& lambda) | |
{ | |
if (lambdaPtr) | |
deleter(lambdaPtr); | |
lambdaPtr = new T(lambda); | |
caller = [](void* t, ArgsType... args)->RetType { return (*static_cast<T*>(t))(args...); }; | |
deleter = [](void* t) { delete(static_cast<T*>(t)); }; | |
} | |
~Holder() | |
{ | |
if (lambdaPtr) | |
deleter(lambdaPtr); | |
} | |
}; | |
int main() | |
{ | |
Holder<bool(int)> holder; | |
cout << boolalpha; | |
{ | |
// both i, and the lambda exist in local scope, and | |
// die when the scope is closed | |
int local=5; | |
holder.set([local](int arg)->bool | |
{ | |
cout << "captured: " << local | |
<< ", arg: " << arg | |
<< endl; | |
return local==arg; | |
}); | |
} | |
bool result = holder.call(5); | |
cout << "equal: " << result << endl; | |
result = holder.call(1); | |
cout << "equal: " << result << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment