Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a class that can save variadic template arguments?

template<typename... Args>
struct A
{
    Args&... args_;
    //
    // error : only function and template parameters can be parameter packs
    //

    A(Args&... args) : args_(args)
    {}
};

int main()
{
    auto a = A(1, 2, 3);
}

My compiler is clang 5.0 with -std=c++1z.

How to define a class that can save variadic template arguments in such a case?

like image 398
xmllmx Avatar asked Mar 26 '17 08:03

xmllmx


People also ask

How do you use Variadic arguments?

It takes one fixed argument and then any number of arguments can be passed. The variadic function consists of at least one fixed variable and then an ellipsis(…) as the last parameter. This enables access to variadic function arguments. *argN* is the last fixed argument in the variadic function.

What is Variadic template in C++?

A variadic template is a class or function template that supports an arbitrary number of arguments. This mechanism is especially useful to C++ library developers: You can apply it to both class templates and function templates, and thereby provide a wide range of type-safe and non-trivial functionality and flexibility.

Which of the following are valid reasons for using variadic templates in C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.

How do Variadic functions work in C?

Function arguments are placed on the stack. So executing sum_squares(2,3) means placing 2 and 3 (amongst some other things) on the stack. Putting these two values on the stack means advancing the stack pointer enough for two int values, placing our two values in the free space.


1 Answers

That's not possible as far as I know. You have to use a std::tuple to store the parameters:

template<typename... Args>
struct A
{
    std::tuple<std::decay_t<Args>...> args_;

    A(Args&&... args) : args_(std::make_tuple(std::forward<Args>(args)...))
    {}
};

As of C++17, you can use std::apply to cal functions with args_ as parameters, instead of unpacking them:

std::apply(func, args_);
like image 82
Rakete1111 Avatar answered Oct 15 '22 23:10

Rakete1111