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

use*_*467 7 c++ variadic-templates perfect-forwarding c++20 parameter-pack

我无法理解如何在 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) - 20
print(const int& value) - 12
print(const int& value) - 14
Run Code Online (Sandbox Code Playgroud)

我期望看到的是以下输出:

输出:

print(const int& value) - 10
print(const int& value) - 20
print(int&& value) - 12
print(int&& value) - 14
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么这种行为是这样的吗?

我尝试编译代码并检查结果。

Nat*_*ica 11

{ args... }一旦创建了一个std::initializer_list将所有元​​素复制到底层 const 对象的临时数组中,您就失去了转发的能力。

相反,您可以使用折叠表达式来调用print参数包的每个成员,例如

template <class... Arg>
void print_each_argument(Arg&&... args) {
    (print(std::forward<Arg>(args)), ...);
}
Run Code Online (Sandbox Code Playgroud)