Skip to content

Instantly share code, notes, and snippets.

@windoze
Created December 9, 2014 15:29
Show Gist options
  • Save windoze/554fd3c52440135882cc to your computer and use it in GitHub Desktop.
Save windoze/554fd3c52440135882cc to your computer and use it in GitHub Desktop.
Call any callable with a string vector or array, use with make_function and make_tuple_indices gists
template<typename Vec, typename Ret, class... Args>
struct function_wrapper;
// function_wrapper
template<typename Vec, typename Ret, class... Args>
struct function_wrapper<Vec, std::function<Ret(Args...)>> {
typedef std::function<Ret(Args...)> function_type;
typedef std::tuple<typename std::decay<Args>::type...> arg_list_type;
typedef Ret result_type;
static constexpr size_t arity=sizeof...(Args);
function_wrapper(function_type &&f) : f_(std::forward<function_type>(f)) {}
template<typename T, size_t N>
T get(const Vec &v) const { return boost::lexical_cast<T>(v[N]); }
template <std::size_t... Indices>
result_type call2(const Vec &v, tuple_indices<Indices...>)
{ return invoke(f_, get<typename std::tuple_element<Indices, arg_list_type>::type, Indices>(v)...); }
size_t get_arity() const { return arity; }
result_type call(const Vec &v)
{ return call2(v, typename make_tuple_indices<std::tuple_size<std::tuple<Args...>>::value>::type()); }
std::function<Ret(Args...)> f_;
};
template<typename Vec, typename F>
auto apply(F f, const Vec &v) -> typename make_function_type<F>::result_type {
typedef detail::function_wrapper<Vec, make_function_type<F>> wrapper;
return wrapper(make_function(std::forward<F>(f))).call(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment