为什么C ++模板接受数组不比一个接受指针(bis)更专业? [英] Why C++ template accepting array is not more specialized than one accepting pointer (bis)?
问题描述
In reference to this question, which has indeed the same title but for which I found an answer in the standard. I have continued to dig the subject and finaly find out an example code for which this answer does not apply.
让我们考虑这段代码:
template<class T> void func(T* buf); //template I
template<size_t N> void func(char (&buf) [N]); //template II
void g(char (&buf)[3])
{
func(buf) //Error: ambiguous function call (Clang, GCC, ICC, MSVC)
}
根据 [temp.func.order]中的部分排序规则和 [temp.deduct.partial] ,如果人们通过执行这段代码来解释此规则,那么 template II 应该比 template I 更专业:
According to the partial ordering rules in [temp.func.order] and [temp.deduct.partial], template II shall be more specialized than template I if one interpreted this rules through the execution of this piece of code:
template <class T> void func1(T* buf) {}
template <std::size_t N> void func2(char (&buf)[N]) {}
struct invented_T{};
constexpr std::size_t invented_N=42;
void is_template_I_more_specialized(invented_T* buf)
{
func2(buf);
//DO NOT COMPILE
// => template I is not more specialized than func2
}
void is_template_II_more_specialized(char (&buf)[invented_N])
{
func1(buf);
//DO COMPILE
// => template II is more specialized than func1
}
因此,根据这种解释,模板II 应该是更专业的.为什么不是这样?
So according to this interpretation, template II should be more specialized. Why would it not be the case?
推荐答案
注释中指出,原因是无法从类型char (&buf)[invented_N]
推导出类型T*
.
As n.m. pointed out in the comment, the reason is that type T*
cannot be deduced from type char (&buf)[invented_N]
.
在 如果P不是引用类型:
If P is not a reference type: 如果A是数组类型,则使用数组到指针标准转换生成的指针类型代替A进行类型推导;否则, If A is an array type, the pointer type produced by the array-to-pointer standard conversion is used in place of A for type deduction; otherwise, ... 此规则仅适用于从函数调用中推断模板参数 .为了推断部分订购期间期间的模板参数,不应用这种转换. This rule only applies for deducing template arguments from a function call. For deducing template arguments during partial ordering, there is no such conversion applying. 在[temp.deduct.partial]/ 6 , 7 . Conversions that can be applied during partial ordering are described in [temp.deduct.partial]/5,6,7. 这篇关于为什么C ++模板接受数组不比一个接受指针(bis)更专业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!is_template_II_more_specialized
中,根据