Undefined number of arguments in C++ [duplicate]

无人久伴 提交于 2019-12-01 20:41:30

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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!