Is there any way in c++ to iterate over function parameter types in compile time? I want to do something like this:
struct null_type {};
float foo(int, bool, char);
get_param_type<foo, 0>::type float_var; // return type
get_param_type<foo, 1>::type int_var; // first arg type
get_param_type<foo, 2>::type bool_var; // second arg type
get_param_type<foo, 3>::type char_var; // third arg type
get_param_type<foo, 4>::type null_type_var;
You can easily write this yourself. First, pack the function parameter types into a tuple:
#include <tuple>
template <typename> struct FnArgs;
template <typename R, typename ...Args>
struct FnArgs<R(Args...)>
{
using type = std::tuple<Args...>;
};
Now you can use the standard tuple API to access the elements:
using FT = FnArgs<decltype(foo)>::type;
std::tuple_element<0, FT> x;
A further specialization for pointers-to-member-function is easily added should you need one.
(You cannot easily get around the decltype, since there is no type deduction for non-type template parameters (yet).)
Here's a version which uses your null_type for out-of-bounds indices:
template <typename, std::size_t, typename = void>
struct get_param_type
{
using type = null_type;
};
template <typename Ret, typename... Args, std::size_t N>
struct get_param_type<Ret(Args...), N, std::enable_if_t<N < (1+sizeof...(Args))>>
{
using type = typename std::tuple_element<N,std::tuple<Ret,Args...>>::type;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With