存储未展开的参数包

Store unexpanded parameter pack

本文关键字:参数 存储      更新时间:2023-10-16

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

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++中尚不允许成员包。你必须求助于使用元组之类的东西,并在使用它时重新扩展包:

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
);