7

我正在type_traits通过新的 C++14 运行时大小的数组测试标头中的一些工具,请考虑以下代码:

int g[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

template <typename T> void print(T &t)
{
    std::cout << "Type id:    " << typeid(T).name() << '\n';
    std::cout << "is_array:   " << std::is_array<decltype(T)>::value << '\n';
    std::cout << "is_pointer: " << std::is_pointer<decltype(T)>::value << '\n';
    std::cout << "extent:     " << std::extent<decltype(T)>::value << '\n';
}

int main()
{
    print(g);
    return 0;
}

静态大小的数组g返回以下输出:

Type id:    A11_i
is_array:   1
is_pointer: 0
extent:     11

A11_i我假设未修改名称是11 个int类型元素的数组,所以这里一切都是正确的,但是使用这个新代码:

void f(std::size_t s)
{
    int a[s];
    print(a);
}

int main()
{
    f(5);
    return 0;
}

我收到错误:

In function 'void f(std::size_t)':
error: no matching function for call to 'print(int [s])'

note: candidate is:
note: template<class T> void print(T&)
note:   template argument deduction/substitution failed:
note:   variable-sized array type 'int [s]' is not a valid template argument

我没想到可以将 size 参数传递给模板,但我期待自动数组到指针的衰减。我猜这个论点T &不适合这种衰减,所以我尝试将模板签名更改为:

template <typename T> void print(T *&t)

结果相似:

In function 'void f(std::size_t)':
error: no matching function for call to 'print(int [s])'

note: candidate is:
note: template<class T> void print(T*&)
note:   template argument deduction/substitution failed:
note:   mismatched types 'T*' and 'int [s]'

而且我注意到运行时大小数组上的大小变量似乎与类型相关(而不是我们得到),这看起来很奇怪。mismatched types 'T*' and 'int [5]'mismatched types 'T*' and 'int [s]'

那么,问题是什么?

  • 为什么我在这个运行时大小的数组中没有得到数组到指针的衰减?
  • 用于调整运行时大小数组大小的变量是运行时大小数组类型的一部分还是我误解了错误?
4

1 回答 1

3

在模板实参推导期间,仅当函数模板形参的类型不是引用时才使用数组到指针的转换。

§14.8.2.1 从函数调用中推导出模板参数 [temp.deduct.call]

1 模板实参推导是通过将每个函数模板形参类型(调用它P)与调用的对应实参类型(调用它)进行比较来完成的,A如下所述。[...]

2 如果P不是引用类型:

  • ifA是数组类型,使用数组到指针标准转换(4.2)产生的指针类型代替Afor类型推导;否则,
  • [...]
于 2015-04-13T17:05:03.710 回答