函数模板参数包问题

problem with function template parameter pack

本文关键字:问题 参数 包问题 函数模板      更新时间:2023-10-16

为什么下面编译失败?

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 部分是否是包?

想象一下,编译器只是通过参数列表,应该直接知道在哪里停止包。