Interaction between default arguments and parameter pack (GCC and clang disagree)

蹲街弑〆低调 提交于 2019-12-23 08:53:54

问题


I expect the following code to compile:

#include <iostream>

template <class Tag = void, class T = int, class... Args>
void print(T val = T{}, Args... args) {
    std::cout << val << ' ' << sizeof...(args) << std::endl;
}

int main() {
    print();
    print(3.14);
    print(0, 1, 2);
}

While it compiles on GCC 5.2 (C++11) despite the unused-but-set-parameter warnings, clang 3.6 (C++11) gives the following error messages:

main.cpp:4:33: error: missing default argument on parameter 'args'
void print(T val = T{}, Args... args) {
                                ^
main.cpp:11:5: note: in instantiation of function template specialization 'print<void, int, int, int>' requested here
    print(0, 1, 2);
    ^
main.cpp:4:33: error: missing default argument on parameter 'args'
void print(T val = T{}, Args... args) {
                                ^
2 errors generated.

So, who is correct?


回答1:


They're both correct, in a sense.

There's a bug in the standard, CWG 1609, making it unclear whether the code is well-formed or not.

On the CWG summary, it seems there was a consensus that clang should be correct in rejecting the code. Then, a few months later, there was a consensus that GCC should be correct in accepting the code. So who knows what'll happen in C++17.




回答2:


Well, as @T.C. has pointed out in the comment and the answer of @LightnessRacesinOrbit, this is a pending CWG issue. Anyway, I just found a workaround:

#include <iostream>

template <class Tag = void, class T, class... Args>
void print(T val, Args... args) {
    std::cout << val << ' ' << sizeof...(args) << std::endl;
}

template <class Tag = void, class T = int>
void print(T val = T{}) {
    std::cout << val << ' ' << 0 << std::endl;
}

int main() {
    print();
    print(3.14);
    print(0, 1, 2);
}


来源:https://stackoverflow.com/questions/34494765/interaction-between-default-arguments-and-parameter-pack-gcc-and-clang-disagree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!