存储未展开的参数包

问题描述 投票:1回答:1

基本上我有一个可变的模板函数,如下所示:

template<typename... Args>
void foo(std::string message, Args... args) {
    //Some nice code
}

我现在想要一个存储值的结构,稍后我用它来调用这个函数。我试过这样的:

template<typename... Args>
struct Foo {
    std::string message;
    Args args;

    Foo(std::string message, Args... args): message(message), args(args) {}
}

int main(int arg, char ** argv) {
    Foo arguments("Hello, World!", 5, "LOL");

    foo(arguments.message, arguments.args);

    return 0;
}

但不幸的是,这不起作用。这有点可行吗?

c++ variadic-templates
1个回答
3
投票

在C ++中不允许使用成员包。您将不得不求助于使用类似元组的东西,并在使用它时重新扩展包:

template<typename... Args>
struct Foo {
    std::string message;
    std::tuple<Args...> args;

    Foo(std::string message, Args&&... args) :
        message(message), args(std::forward<Args>(args)...) {}
    //                         ^
    // I added perfect forwarding to reduce copies
}

然后再次将元组转换为包,您可以使用std::apply

std::apply(
    [&](auto&&... args) {
        foo(arguments.message, args...);
    },
    arguments.args // this is the tuple, not a pack
);
© www.soinside.com 2019 - 2024. All rights reserved.