C++ parameter pack access out of range

198 Views Asked by At

I'm kinda new to parameter pack and I ran into a problem related to out of range index. To simplify the problem, I want to access the n-th element (lets say 3rd) in parameter pack inside the function. If the function call does not pass 3 params (or more), return nullptr. Maybe there is a recursive solution to safely ignore the case of less parameters?

template <int I, class... Ts>
decltype(auto) get_element(Ts&&... ts) {
    return std::get<I>(std::forward_as_tuple(ts...));
}

    template <typename... Args>
    void foo(Args ... args)
    {
        auto p = get_element<3>(args...);
    }


int main()
{
    int a = 1;
    foo(a);
    return 0;
}

Error C2338 tuple index out of bounds
Error C2672 'std::get': no matching overloaded function found

1

There are 1 best solutions below

5
On

Try this (since C++17)

template <int I, class... Ts>
  decltype(auto) get_element(Ts&&... ts) {
  if constexpr (I < sizeof...(Ts))
    return std::get<I>(std::forward_as_tuple(ts...));
  else
    return nullptr;
}

Now you get only compiler warnings for unused parameters in doubt. That might be intented I think since you already bypassed compile time safety this way.

Also keep in mind that std::get is zero-based! So for a working example, you need not three but at least four parameters.