Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over function parameter types in compile time

Tags:

c++

templates

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;
like image 338
ivaigult Avatar asked Oct 24 '25 17:10

ivaigult


2 Answers

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).)

like image 83
Kerrek SB Avatar answered Oct 26 '25 05:10

Kerrek SB


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;
};
like image 22
TartanLlama Avatar answered Oct 26 '25 07:10

TartanLlama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!