Reputation: 11499
I have a std::vector
of arguments and I would like to call a function with them. Is there any way to do this?
In particular the function is the mysqlx
select function and the arguments are the columns I'm trying to query; they will all be of type std::string
. The purpose of the function is to reduce duplication in the codebase.
(This seems like a generally useful topic, but I could not find an answer through search. If I missed it and this has already been answered, please point me to the question and close this as a duplicate, thanks.)
Upvotes: 2
Views: 1117
Reputation: 63392
You can do it, up to a compile time maximum number of arguments. It isn't pretty.
using result_type = // whatever
using arg_type = // whatever
using args_type = const std::vector<arg_type> &;
using function_type = std::function<result_type(args_type)>;
template <size_t... Is>
result_type apply_vector_static(args_type args, std::index_sequence<Is...>)
{
return select(args[Is]...);
}
template<size_t N>
result_type call_apply_vector(args_type args)
{
return apply_vector_static(args, std::make_index_sequence<N>());
}
template <size_t... Is>
std::map<size_t, function_type> make_funcs(std::index_sequence<Is...>)
{
return { { Is, call_apply_vector<Is> }... };
}
result_type apply_vector(args_type args)
{
// Some maximum limit
static const auto limit = std::make_index_sequence<50>();
static const auto funcs = make_funcs(limit);
return funcs.at(args.size())(args);
}
Upvotes: 4