模板参数推导:哪个编译器就在这里?

Template argument deduction: which compiler is right here?

考虑以下代码:

template<int N>
class Vector
{
};

#include <array>

template<int N>
void doWork(const Vector<N>&, const std::array<int,N>&)
{
}

int main()
{
    std::array<int,3> arr;
    Vector<3> vec;
    doWork(vec,arr);
}

这里的Vector表示一个class,是在第三方库中定义的,而std::array已知取其元素个数为std::size_t

我试过用 clang-3.6 和 g++-5.1 编译它。 Clang 毫无怨言地工作,而 g++ 给出以下错误:

test.cpp: In function ‘int main()’:
test.cpp:17:19: error: no matching function for call to ‘doWork(Vector<3>&, std::array<int, 3ul>&)’
     doWork(vec,arr);
                   ^
test.cpp:9:6: note: candidate: template<int N> void doWork(const Vector<N>&, const std::array<int, N>&)
 void doWork(const Vector<N>&, const std::array<int,N>&)
      ^
test.cpp:9:6: note:   template argument deduction/substitution failed:
test.cpp:17:19: note:   mismatched types ‘int’ and ‘long unsigned int’
     doWork(vec,arr);
                   ^
test.cpp:17:19: note:   ‘std::array<int, 3ul>’ is not derived from ‘const std::array<int, N>’

我可以通过在 doWork() 的第二个参数中将 N 转换为 std::size_t 或调用 doWork<3>() 来解决这个问题,但这不会教育我.

所以我宁愿先问:哪个编译器就在这里?我真的在代码中做错了什么(所以 clang 太宽容了),还是它确实有效的 C++(所以 g++ 有一个错误)?

我相信 gcc 在这里是正确的,如果我们去草案 C++11 标准部分 14.8.2.5 [temp.deduct.type] 它说:

If, in the declaration of a function template with a non-type template-parameter, the non-type templateparameter is used in an expression in the function parameter-list and, if the corresponding template-argument is deduced, the template-argument type shall match the type of the template-parameter exactly, except that a template-argument deduced from an array bound may be of any integral type.144 [ Example:

template<int i> class A { /* ... */ };
template<short s> void f(A<s>);
void k1() {
A<1> a;
f(a); // error: deduction fails for conversion from int to short
f<1>(a); // OK
}

[...]

我们可以看看是否将您的代码更改为:

doWork<3>(vec,arr);

gcc 不会发出错误,clang 也不会。

如果我们试试这个例子:

template<int N>
void doWorkB( std::array<int,N>&)
{
}

//...

doWorkB(arr);

clang 现在会产生错误 (see it live):

note: candidate template ignored: substitution failure : deduced non-type template argument does not have the same type as the its corresponding template parameter ('unsigned long' vs 'int')
void doWorkB( std::array<int,N>&)
     ^

如果我们交换参数顺序,您的原始案例也会在 clang 中中断:

void doWork( const std::array<int,N>&, const Vector<N>& )