这是关于gcc 4.9.2和clang 3.5.2存在尖锐分歧的一点.该程序:
template<typename ...Ts>
int foo(int i = 0, Ts &&... args)
{
return i + sizeof...(Ts);
}
int main()
{
return foo();
}
Run Code Online (Sandbox Code Playgroud)
编译没有gcc(-std=c++11 -Wall -pedantic)的评论.Clang说:
error: missing default argument on parameter 'args'
Run Code Online (Sandbox Code Playgroud)
随着foo修订为:
template<typename ...Ts>
int foo(int i = 0, Ts &&... args = 0)
{
return i + sizeof...(Ts);
}
Run Code Online (Sandbox Code Playgroud)
clang没有抱怨,但gcc说:
error: parameter pack ‘args’ cannot have a default argument
Run Code Online (Sandbox Code Playgroud)
哪个编译器是对的?
以下代码适用于gcc-4.8.2
#include <iostream>
using namespace std;
template<typename... Args>
void func(Args... args, int optional = 0)
{
cout << optional << endl;
}
int main()
{
func(1);
func(2.1f); // converts 2.1 to int as 'optional' parameter
func<float>(3.3f); // Fine, prints '0'
func(); // gcc OK, fails to compile with clang-3.5
}
Run Code Online (Sandbox Code Playgroud)
它输出:
$ ./a.out
1
2
0
0
Run Code Online (Sandbox Code Playgroud)
但是如果用clang-3.5编译失败,
test_variadic.cpp:15:2: error: no matching function for call to 'func'
func();
^~~~
test_variadic.cpp:5:6: note: candidate function template not viable: requires at least argument …Run Code Online (Sandbox Code Playgroud)