为了避免混淆,我非常理解数组和指针之间的区别,衰减到指针的概念,以及 C++ 中通过引用传递数组的概念等。
我的问题是特别是编译器用来从一组重载候选函数中选择一个函数的规则,当一个重载采用数组引用时,并且另一个重载采用指针。
例如,假设我们有:
template <class T, std::size_t N>
void foo(const T (&arr)[N])
{
std::cout << "Array-reference overload!" << std::endl;
}
template <class T>
void foo(const T* ptr)
{
std::cout << "Pointer overload!" << std::endl;
}
如果我们尝试调用函数模板 foo()
如下:
const char arr[2] = "A";
foo(arr);
... 那么我的期望是编译器会选择第一个 重载,即采用数组引用的重载。
但是,使用 GCC 4.9.2,如果我编译上面的代码,我会得到一个错误:
test.cpp:28:9: error: call of overloaded ‘foo(const char [2])’ is ambiguous
我不清楚为什么这两个重载都被编译器视为同样好的候选者,因为第一个重载与类型完全匹配,而第二个重载需要额外的衰减到指针步骤。
现在,我可以通过显式使用 type_traits
来实现上述重载,如下所示:
template <class T, std::size_t N>
void foo(const T (&arr)[N])
{
std::cout << "Array-reference overload!" << std::endl;
}
template <class T>
void foo(T ptr, typename std::enable_if<std::is_pointer<T>::value>::type* = 0)
{
std::cout << "Pointer overload!" << std::endl;
}
在这种情况下,程序会编译并选择采用数组引用的重载。但是,我不明白为什么这个解决方案是必要的。我想了解为什么当传递的参数是一个数组时,为什么编译器认为需要衰减到指针的函数与数组引用一样可能是重载候选者。
最佳答案
the first overload matches the type exactly, whereas the second overload requires an extra decay-to-pointer step.
因为在检查 ranking of implicit conversion sequences 时在 overload resolution , array-to-pointer conversion被认为是完全匹配,因此第二个重载与第一个重载具有相同的等级。
来自标准,$16.3.3.1.1 Standard conversion sequences [over.ics.scs] Table 13 — Conversions
Conversion Category Rank Subclause No conversions required Identity Exact Match ... ... Array-to-pointer conversion Lvalue Transformation Exact Match [conv.array] ... ...
值得注意的是,“无需转换”(即第一次重载的情况)的排名也是“完全匹配”。
关于c++ - 通过引用传递数组与传递指针的函数参数绑定(bind)规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44815376/