新しい 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個の要素の配列なので、ここではすべて正しいですが、この新しいコードを使用すると、次のようになります。
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
サイズ引数がテンプレートに渡されるとは思っていませんでしたが、配列からポインターへの自動減衰が予想されていました。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
]'
それで、質問は何ですか?
- この実行時サイズの配列で配列からポインターへの減衰が得られないのはなぜですか?
- 実行時サイズの配列のサイズを変更するために使用される変数は、実行時サイズの配列の型の部分ですか、それともエラーを誤解していますか?