运行时大小的数组和指针衰减
Runtime sized arrays and pointer-decay
我正在通过新的 C++14 运行时大小的数组测试type_traits
标头中的一些工具,请考虑以下代码:
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
是int类型的11个元素的rray 所以这里一切都是正确的,但使用此新代码:
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
]'
)这看起来很奇怪。
那么,问题是什么呢?
- 为什么我在这个运行时大小的数组中没有得到数组到指针的衰减?
- 用于调整运行时大小数组大小的变量是运行时大小数组类型的一部分,还是我误解了错误?
在模板参数推导期间,仅当函数模板参数的类型不是引用时才使用数组到指针的转换。
§14.8.2.1 从函数调用中推导模板参数 [温度扣除呼叫]
1 通过比较每个函数来推断模板参数 模板参数类型(调用它
P
),其类型为 调用的相应参数(调用它A
),如下所述。 [...]2 如果
P
不是引用类型:
- 如果
A
是数组类型,则使用数组到指针标准转换 (4.2) 生成的指针类型代替 的A
类型扣除;否则- [...]
相关文章:
- 为什么这些函数不衰减到函数指针?
- 为什么多维数组中的空字符串文本衰减为空指针?
- 从原始指针(衰减的 C 样式数组)和大小生成范围::视图
- 数组变量衰减为指针
- 如果我只有指向第一个数组元素的指针,考虑到数组衰减,是否可以找到数组的长度?
- 在分配给指针到固定数组期间没有指针衰减
- 如果一个函数通过引用返回一个数组,它是指针的衰减吗?
- 推断衰减到函数指针的 lambda 类型
- 应该非捕获通用的lambdas衰减以发挥指针
- 数组衰减为指针和重载分辨率
- 运行时大小的数组和指针衰减
- 编译器在数组到指针衰减存储中生成的指针在哪里
- 为什么指针衰减优先于推导的模板
- 有没有办法避免数组到指针衰减
- 为什么数组类型不会衰减到类模板的指针
- 我能逆转数组到指针衰减的过程吗?
- 数组到指针衰减问题
- 为什么在模板函数中数组衰减为指针?
- 数组衰减为Lambda指针
- 如果通过模板函数中的 const 引用传递,数组不会衰减到指针