小编use*_*467的帖子

如何在C++中完美转发函数参数包的元素

我无法理解如何在 C++ 中转发参数包的元素。请以下面的代码为例:

#include <iostream>

void print(const int& value) {
    std::cout << "print(const int& value) - " << value << std::endl;
}

void print(int&& value) {
    std::cout << "print(int&& value) - " << value << std::endl;
}

template <class... Arg>
void print_each_argument(Arg&&... args) {
    for(auto&& a: { args... }) {
        print(std::forward<decltype(a)>(a));
    }
}

int main() {
    int some_value = 10;
    int other_value = 20;
    print_each_argument(some_value, other_value, 12, 14);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

print(const int& value) - 10
print(const int& value) …
Run Code Online (Sandbox Code Playgroud)

c++ variadic-templates perfect-forwarding c++20 parameter-pack

7
推荐指数
1
解决办法
262
查看次数