c++ - 通过可变参数模板传递右值引用时出现编译器错误

标签 c++ templates c++11 variadic-templates rvalue-reference

有一项要求,我需要通过可变参数模板将右值从 1 个函数传递到另一个函数。为了避免真正的代码复杂性,下面是使用 int 的最小示例:

void Third (int&& a)
{}

template<typename... Args>
void Second (Args&&... args) {
  Third(args...);
}

void First (int&& a) {
  Second(std::move(a));  // error: cannot bind ‘int’ lvalue to ‘int&&’
  Third(std::move(a));  // OK
}

int main () {
  First(0);
}

First(0) 被正确调用。如果我直接调用 Third(int&&),那么使用 std::move() 就可以正常工作。但是调用 Second(Args&&...) results in :

error: cannot bind ‘int’ lvalue to ‘int&&’
   Third(args...);        ^
note:   initializing argument 1 of ‘void Third(int&&)’
 void Third (int&& a)

Second(Args&&...)成功编译的正确方法是什么?

仅供引用:在实际代码中,Second(Args&&...) 是左值、右值和右值引用的混合。因此,如果我使用:

Third(std::move(args...));

it works .但是当参数混合时,它就会出现问题。

最佳答案

你必须使用std::forward:

template<typename... intrgs>
void Second (intrgs&&... args) {
  Third(std::forward<intrgs>(args)...);
}

关于c++ - 通过可变参数模板传递右值引用时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809416/

相关文章:

c++ - "use -D_SCL_SECURE_NO_WARNINGS"是什么意思?

c++ - 将类似的功能代码组合到模板中

python - 作为参数的嵌套模板函数

c++ - 在 C++ 程序 (MFC) 中查找从何处加载 dll

c++ - 可以替换 std::thread 对象吗?

c++ - C++ 中的指针初始化(或缺少)

c++ - C++17 中的歧义错误(模板模板参数和默认参数问题)

c++ - 使用 std::remove_reference 获取 STL 容器的元素迭代器

c++ - 下面显示的片段在 Coliru 和 Ideone 中编译,但根据 iso § 8.5 p6 它不应该,或者我错过了什么?

c++ - 在基于范围的 for 循环中查找具有连续内存的序列中元素的位置