函数模板参数包问题
problem with function template parameter pack
为什么下面编译失败?
inline Obj init_output_string() { return open_output_string(); }
template<typename... Args>
Obj init_output_string(Args... prev, int last)
{
Obj port(init_output_string(prev...));
write_char(port, last);
return port;
}
int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);
(MSVC 的错误'init_output_string': no overloaded function takes 2 arguments
,g++ 给出了类似的错误(。
但以下变体确实可以编译
inline Obj init_output_string() { return open_output_string(); }
template<typename... Args>
Obj init_output_string(int first, Args... rest)
{
Obj port(init_output_string(rest...));
write_char(port, first);
return port;
}
int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);
区别在于字符的书写顺序。我可以很容易地解决这个问题,但我很好奇我的第一个例子打破了什么规则。
您的构造格式不正确。见 https://en.cppreference.com/w/cpp/language/parameter_pack
在函数模板中,模板参数包可能更早出现 在列表中,前提是可以从中推断出以下所有参数 函数参数,或具有默认参数:
给出的示例是(在您的情况下是后者(:
template<typename... Ts, typename U>
struct Invalid; // Error: Ts.. not at the end
template<typename ...Ts, typename U, typename=void>
void valid(U, Ts...); // OK: can deduce U
// void valid(Ts..., U);
// Can't be used: Ts... is a non-deduced context in this position
问题是"如何推断出在哪里停止 int 离开包"? 您的最后一个 int 部分是否是包?
想象一下,编译器只是通过参数列表,应该直接知道在哪里停止包。
相关文章:
- C++转换参数初始化问题
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 标准::enable_if 和标准::is_arithmetic 作为模板参数的问题
- enable_if中参数包的大小问题
- 构造函数 (C++) 中的 char 指针参数存在问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++复杂情况的比较器通过参数问题
- 调试模板时出现问题.专门针对 Linux GCC 7、GCC 6、GCC 5、GCC 4.9 错误构建失败:模板参数 1
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 模板<类型名称...参数>的问题
- C++17 中的歧义错误(模板模板参数和默认参数问题)
- constexpr 运算符重载使用参数的问题
- 通过命令行参数获取llvm ir文件时面临问题
- 函数中使用的函数指针的参数的问题
- 我在生成返回为数不多的模板化参数之一cpp的函数时遇到问题
- 从命令行获取参数时出现问题
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- C++:关于for语句和参数的一般问题
- 字符串打印机问题:参数 X 没有从“char (*)[xx]”到“char**”的已知转换