Skip to content

Instantly share code, notes, and snippets.

@enobayram
Last active October 28, 2015 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enobayram/dce92b468423a8ef6882 to your computer and use it in GitHub Desktop.
Save enobayram/dce92b468423a8ef6882 to your computer and use it in GitHub Desktop.
#include <functional>
#include <list>
#include <boost/any.hpp>
using boost::any;
using std::list;
// list_cast :: list<any> -> list<T>
template<class T>
list<T> list_cast(list<any> l) {
list<T> result;
for(any elem: l) {
result.push_back(any_cast<T>(elem));
}
return result;
};
class MkList {
std::function<std::list<any>(any)> f;
public:
// MkList constructor instantiates a type-erased version
// of any polymorphic (template) function object
template <class INPUT_FUNC_T>
MkList(INPUT_FUNT_T in_f): {
f = [in_f](any arg) { return in_f(arg); };
}
// MkList() type erases an arg, passes to f and type-casts the result
template <class T>
std::list<T> operator()(T arg) {
any type_erased_arg = arg;
std::list<any> type_erased_result = f(type_erased_arg);
return list_cast<T>(type_erased_result);
}
};
// Now suppose we have \x -> [x] translated to C++ as
struct to_list {
template <class T>
list<T> operator()(T arg) {
list<T> result;
result.push_back(arg);
return result;
}
}
// or as (C++14)
auto to_list2 = [](auto arg) {
list<decltype(arg)> result;
result.push_back(arg);
return result;
}
// We can define singleton as:
auto singleton = MkList(to_list());
// or
auto singleton2 = MkList(to_list2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment