Is there any way in c++11/14 to write variadic template function like this:
template <typename ReturnType, typename Args...>
std::function<ReturnType()> bindArgumentsFromTuple
(std::function<ReturnType(Args... args)> f,
const std::tuple<Args...>& t)
that binds elements of tuple t to function f as arguments (such that the number of elements and its types are identical in function arguments and tuple)?
Example of usage:
void dummy_print(int i, double d)
{
std::cout << i << "," << d << '\n';
}
void dummy_print2(int i, double d, std::string& s)
{
std::cout << i << "," << d << "," << s << '\n';
}
int main() {
std::tuple<int,double> t(77,1.1);
std::tuple<int,double,std::string> t2(1,2.0,"aaa");
auto f1 = bindArgumentsFromTuple(dummy_print, t);
f1();
auto f2 = bindArgumentsFromTuple(dummy_print2, t2);
f2();
return 0;
}
template <typename F, typename T, std::size_t... indices>
auto bindTuple(F&& f, T&& t, std::index_sequence<indices...>) {
return std::bind(std::forward<F>(f), std::get<indices>(std::forward<T>(t))...);
}
template <typename F, typename T>
auto bindTuple(F&& f, T&& t) {
return bindTuple(std::forward<F>(f), std::forward<T>(t),
std::make_index_sequence<std::tuple_size<std::decay_t<T>>{}>{});
}
The above will support anything tuple-esque, ie std::array
, std::tuple
, etc., while regarding placeholder arguments. Demo .
With std::index_sequence
, you may do something like:
template <typename ReturnType, typename ...Args, std::size_t ... Is>
std::function<ReturnType()>
bindArgumentsFromTuple_impl(std::function<ReturnType(Args...)> f,
const std::tuple<Args...>& t, std::index_sequence<Is...>)
{
return [=]() { return f(std::get<Is>(t)...);};
}
template <typename ReturnType, typename ...Args>
std::function<ReturnType()>
bindArgumentsFromTuple(std::function<ReturnType(Args...)> f,
const std::tuple<Args...>& t)
{
return bindArgumentsFromTuple_impl(f, t, std::index_sequence_for<Args...>{});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.