Undefined number of arguments in C++ [duplicate]

2019-02-23 22:08发布

问题:

This question already has an answer here:

  • Variable number of arguments in C++? 15 answers

Can I overload my function to do something with a lot of arguments as in JavaScript. For example:

function f()
{
  alert(arguments[0]);
}

f(4); // will alert 4 

Can I do the same thing in C++ ?

回答1:

You can use variadic template arguments and tuples:

#include <tuple>
#include <iostream>

template <class... Args>
void f(Args&&... args)
{
    auto arguments = std::make_tuple(std::forward<Args>(args)...);
    std::cout << std::get<0>(arguments);
}

void f() {} // for 0 arguments

int main()
{
    f(2, 4, 6, 8);
}

Live Demo

For bounds checking, try the following:

#include <tuple>
#include <iostream>

template <class... T>
struct input
{
    std::tuple<T...> var;
    input(T&&... t) : var(std::forward<T>(t)...) {}

    template <std::size_t N, bool in_range = 0 <= N && N < std::tuple_size<decltype(var)>::value>
    auto get() -> typename std::tuple_element<in_range ? N : 0, std::tuple<T...>>::type
    {
        return std::get<in_range ? N : 0>(var);
    }
};

template <class... Args>
void f(Args&&... args)
{
    auto arguments = input<Args...>(std::forward<Args>(args)...);

    std::cout << arguments.template get<9>();
}

void f() {} // for 0 arguments

int main()
{
    f(2, 4, 6, 8);
}

Update: If you need the first argument then you simply want a function which exposes that first argument by separating it from the parameter pack:

template<class Head, class... Tail>
void foo(Head&& head, Tail&&... tail);

If this is not satisfactory (i.e you want to get the nth-argument), you can unpack the arguments into a std::tuple<> and retrieve an element with std::get<>:

template<class... Args>
void foo(Args&&... args)
{
    auto t = std::forward_as_tuple(std::forward<Args>(args)...);
    print(std::get<5>(t));
}