简体   繁体   English

功能模板参数包出现问题

[英]problem with function template parameter pack

Why does the following fail to compile? 为什么以下内容无法编译?

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);

(error is 'init_output_string': no overloaded function takes 2 arguments for MSVC, g++ gives a similar error). (错误是'init_output_string': no overloaded function takes 2 arguments为MSVC 'init_output_string': no overloaded function takes 2 arguments ,g ++给出了类似的错误)。

But the following variation does compile 但是以下变化确实可以编译

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);

The difference being the order in which the characters are written. 区别在于字符的写入顺序。 I can work around this easily enough, but I'm curious to know what rule my first example is breaking. 我可以很容易地解决这个问题,但是我很好奇我的第一个示例违反了什么规则。

Your construction is illformed. 您的结构变形。 see https://en.cppreference.com/w/cpp/language/parameter_pack 参见https://en.cppreference.com/w/cpp/language/parameter_pack

In a function template, the template parameter pack may appear earlier in the list provided that all following parameters can be deduced from the function arguments, or have default arguments: 在函数模板中,模板参数包可能会出现在列表的前面,但前提是可以从函数参数中推导以下所有参数,或使用默认参数:

the example given is(the latter in your case): 给出的示例是(在您的情况下为后者):

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

the problem is "how to deduce where to stop the int fro the pack"? 问题是“如何推论如何从包装中取出情报”? is your last int part of the pack or not? 您的最后一个int包中的一部分吗?

Imagine the compiler is just going thru the list of parameters and should directly know where to stop the pack. 想象一下,编译器只是遍历参数列表,并且应该直接知道在哪里停止打包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM