Trying to expand on the example found here: https://stackoverflow.com/a/17974752
Basically, I'd like to deduce the number of arguments from the function passed in automatically (which obviously wouldn't work for overloaded functions). I'd like this to also work with functors and lambdas.
It's failing to compile the call to call_helper
: error: parse error in template argument
I can't seem to figure out how to pass in the constexpr that returns the number of arguments as a template argument.
This is what I have so far:
#include <vector>
template <typename R, typename ... T>
constexpr std::size_t get_args_count( R(*f)(T ...))
{
return sizeof...(T);
}
template< std::size_t... Ns >
struct indices {
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices {
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
typedef indices<> type;
};
void abc(int) {}
void abc2(int, int) {}
// helper function because we need a way
// to deduce indices pack
template<typename Func, size_t... Is>
void call_helper2(Func f, const std::vector<int>& args, indices<Is...>)
{
f( args[Is]... ); // expand the indices pack
}
template<typename Func, size_t N>
void call_helper(Func f, const std::vector<int>& args)
{
call_helper2(f, args, typename make_indices<N>::type());
}
template<typename Func>
void call(Func f, const std::vector<int>& args)
{
if (args.size() < get_args_count(f)) throw 42;
call_helper<get_args_count(decltype(f))>(f, args); // error: parse error in template argument list
}
int main()
{
struct F
{
void operator()(int, int, int, int) {}
};
std::vector<int> v(4);
call(&abc2, v);
call(&abc, v);
call([&](int, int, int) { (void)v.empty(); }, v);
call(F(), v);
}
What am I missing or doing wrong? Any help is appreciated.
EDIT: Added functor and lambda use cases