C++ 標準テンプレート (STL) - 型のサポート (型の変更、指定された配列型からの次元の削除、std::remove_extent)

タイププロパティ


type 属性は、型のプロパティをクエリまたは変更するためのコンパイル時のテンプレート ベースの構造を定義します。

<type_traits> ヘッダーで定義されたテンプレートを特殊化しようとすると、std::common_type が説明どおりに特殊化できる場合を除き、未定義の動作が発生します。

<type_traits> ヘッダー ファイルで定義されたテンプレートは、特に指定されない限り、不完全な型でインスタンス化できますが、不完全な型による標準ライブラリ テンプレートのインスタンス化は一般に禁止されています。
 

型の変更

型変更テンプレートは、テンプレート パラメーターに変更を適用することにより、新しい型定義を作成します。結果の型には、メンバーの typedef 型を通じてアクセスできます。
 

指定された配列型から次元を削除します

std::remove_extent

テンプレート<クラス T >
struct Remove_extent;

(C++11以降)

TX 型の配列の場合、X < と等しいメンバー typedef を指定します。 a i=4> 、それ以外の場合は です。 T が多次元配列の場合、最初の次元のみが削除されることに注意してください。 typetypeT

メンバータイプ

タイプ 意味
type T要素の種類

補助タイプ

テンプレート< class T >
using Remove_extent_t = typename Remove_extent<T>::type;

(C++14以降)

可能な実装

template<class T>
struct remove_extent { typedef T type; };
 
template<class T>
struct remove_extent<T[]> { typedef T type; };
 
template<class T, std::size_t N>
struct remove_extent<T[N]> { typedef T type; };

通話例

#include <iostream>
#include <iterator>
#include <algorithm>
#include <type_traits>

//std::rank(C++11)获取数组类型的维数
//std::extent(C++11)获取数组类型在指定维度的大小

template<class A>
typename std::enable_if< std::rank<A>::value == 1 >::type
print_1d(const A& a)
{
    std::copy(a, a + std::extent<A>::value,
              std::ostream_iterator<typename std::remove_extent<A>::type>(std::cout, " "));
    std::cout << std::endl;
}

int main()
{
    int a[][5] = {
   
   {1, 2, 3, 7, 8}, {4, 5, 6, 9, 0}};
    //  print_1d(a); // 编译时错误
    print_1d(a[0]);
    print_1d(a[1]);
    std::cout << std::endl;

    char str[][5] = {
   
   {'a', 'b', 'c', 'd', 'f'}, {'h', 'i', 'j', 'k', 'l'}};
    print_1d(str[0]);
    print_1d(str[1]);
    std::cout << std::endl;

    return 0;
}

出力

1 2 3 7 8
4 5 6 9 0

a b c d f
h i j k l

おすすめ

転載: blog.csdn.net/qq_40788199/article/details/134618745