jeudi 30 mai 2019

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

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.

Aucun commentaire:

Enregistrer un commentaire