How do I create a typedef for the first parameter of a parameter pack

advertisements

How can I get access to the individual items in a parameter pack?

Given the following:

template<typename T>
struct X {};

template<class R, class... Args>
struct X<R (Args...)>
{
  // how can I create a typedef for the first parameter
  // basically I want to do something like if arg1 exists typedef it
  // pseduo code below

  if (Args[0])
   typedef typename Args[0] Parameter1
}

Otherwise I might have to do something like this but was hoping to keep it generic

template<class R, class... Args>
struct X<R (Arg1, Args...)>
{

}


You can use std::tuple_element:

template<typename... Args>
struct arg
{
    template<int N>
    using type = typename std::tuple_element<N, std::tuple<Args...>>::type;
};

template<typename R, typename... Args>
struct X<R (Args...)>
{
    using first = typename arg<Args...>::template type<0>;
};

That will allow you to access an arbitrary type through a compile-time index. You can also use static_assert to assert at compile-time that a parameter pack has at least one element.

template<typename... Args>
struct has_first_arg : std::true_type { };

template<>
struct has_first_arg<> : std::false_type { };

template<typename R, typename... Args>
struct X<R (Args...)>
{
    static_assert(has_first_arg<Args...>::value,
                  "Parameter pack must have at least one element");
};