在下面的代码中,尝试通过参数包移动构造失败。
我缺少什么以及如何修复代码以运行所有 4 个变体?
#include <utility>
struct File
{
File(const char *filename) {}
};
template<typename T>
struct InflateInput
{
template<typename ...Args>
InflateInput(int header, Args ...args) : source(args...) {}
T source;
};
template<typename T>
struct DeflateInput
{
template<typename ...Args>
DeflateInput(int level, int header, Args ...args) : source(args...) {}
DeflateInput(T &&stream, int level, int header) : source(std::move(stream)) {}
T source;
};
int main()
{
// case 1: ok
File file{"filename"};
DeflateInput deflate1(std::move(file), 5, 0);
// case 2: ok
DeflateInput deflate2(File{"filename"}, 5, 0);
// case 3: error :-(
InflateInput<DeflateInput<File>> inflate1(0,
File{"filename"}, 9, 0);
// case 4: ok
InflateInput<DeflateInput<File>> inflate2(0,
9, 0,
"filename");
return 0;
};
编译器错误是 (-std=c++2a) 如下:
1.cpp: In instantiation of 'InflateInput<T>::InflateInput(int, Args ...) [with Args = {File, int, int}; T = DeflateInput<File>]':
1.cpp:35:26: required from here
1.cpp:13:58: error: no matching function for call to 'DeflateInput<File>::DeflateInput(File&, int&, int&)'
InflateInput(int header, Args ...args) : source(args...) {}
^
最佳答案
缺少完美转发。试试下面
template<typename ...Args>
InflateInput(int header, Args&& ...args) : source(std::forward<Args&&>(args)...) {}
下面的构造函数接受 T
类型的右值引用。但是 InflateInput
正在调用一个参数 (Args
),它是一个左值。因此编译器错误。
DeflateInput(T &&stream, int level, int header) : source(std::move(stream)) {}
您可以重现相同的错误,例如,
DeflateInput deflate3(file, 5, 0)
关于c++ - 参数包和移动语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54206926/