Consider I have the following:
void bar(int a, int b)
{
}
template<typename F, typename... Args>
void foo(F function, Args... args>
{
function(args...);
}
I would like to have some kind of way to only pass the necessary amount of arguments to the function, so that I would be able to do the following, which should result in a call to bar with 1, 2 as arguments discarding the 3. Without knowing how many arguments the passed in function type F needs.
foo(bar, 1, 2, 3);
foo([](int a, int b){}, 1, 2, 3);
When I try to use the below function traits:
namespace detail
{
template<typename F, std::size_t... Is, class Tup>
void call_discard_impl(F&& func, std::index_sequence<Is...>, Tup&& tup)
{
std::forward<F>(func)(std::get<Is>(tup)...);
}
}
template<typename F, typename... Args>
void call_discard(F&& func, Args&&... args)
{
detail::call_discard_impl(std::forward<F>(func),
std::make_index_sequence<function_traits<F>::num_args>{},
std::forward_as_tuple(args...));
}
I get:
error C2510: 'F': left of '::' must be a class/struct/union
error C2065: '()': undeclared identifier
error C2955: 'function_traits': use of class template requires template argument list
On:
template <typename F>
struct function_traits : public function_traits<decltype(&F::operator())>
{}
I did get the member function version working which did not require the function traits:
namespace detail
{
template<typename O, typename R, typename... FunArgs, std::size_t... Is, class Tup>
void call_discard_impl(O* obj, R(O::*mem_func)(FunArgs...), std::index_sequence<Is...>, Tup&& tup)
{
((*obj).*mem_func)(std::get<Is>(tup)...);
}
}
template<typename O, typename R, typename... FunArgs, typename... Args>
void call_discard(O* obj, R(O::*mem_func)(FunArgs...), Args&&... args)
{
detail::call_discard_impl(obj, mem_func,
std::make_index_sequence<sizeof...(FunArgs)>{},
std::forward_as_tuple(args...));
}