【发布时间】:2019-01-15 21:16:33
【问题描述】:
在以下代码中,尝试通过参数包移动构造失败。
我缺少什么以及如何修复代码以运行所有 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...) {}
^
【问题讨论】:
-
错误信息是什么?
-
T在这两种情况下都是不可演绎的上下文。您需要向DeflateInput提供模板参数。我看不出//case 1: ok或// case 2: ok的评论是如何站得住脚的,即使它甚至无法编译。此外,如果您真的想按照自己的意愿工作,这应该使用适当的转发引用。 -
为什么
DeflateInput有两个构造函数? -
@WhozCraig 在 C++17 中被允许。
-
@Chameleon 感谢您通过添加 C++17 标记进行澄清。
标签: c++ c++17 variadic-templates perfect-forwarding