Search code examples
c++variadic-templatesparameter-pack

Parameters pack with single function


Below code extracts n-th argument of function formatted as string. How can I implement it without providing the second function? Is it possible at all?

template <typename Type, typename ...Args>
static std::string getArgument(unsigned argumentIndex, Type value, Args... args)
{
    if (argumentIndex != 0)
        return getArgument(argumentIndex - 1, args...);
    else
        return std::to_string(value);
}

static std::string getArgument(unsigned argumentIndex)
{
    return std::string();
}

Solution

  • Thanks @DrewDormann for getting the solution started. Here it is, rearranged to have the behavior of the original code for index-out-of-range:

    template <typename Type, typename ...Args>
    static std::string getArgument(unsigned argumentIndex, Type value, Args... args)
    {
        if (argumentIndex == 0)
            return std::to_string(value);
        if constexpr ( sizeof...(Args) > 0 ) {
            return getArgument(argumentIndex - 1, args...);
        }
        return std::string();
    }
    

    The one-argument overload of the function is eliminated; a consequence is that the user can't call the function with only the argumentIndex. My understanding of the question is that OP wanted this change.