タイププロパティ
type 属性は、型のプロパティをクエリまたは変更するためのコンパイル時のテンプレート ベースの構造を定義します。
<type_traits> ヘッダーで定義されたテンプレートを特殊化しようとすると、std::common_type が説明どおりに特殊化できる場合を除き、未定義の動作が発生します。
<type_traits> ヘッダー ファイルで定義されたテンプレートは、特に指定されない限り、不完全な型でインスタンス化できますが、不完全な型による標準ライブラリ テンプレートのインスタンス化は一般に禁止されています。
その他の変換
コンパイル時のブール値に基づいて 1 つまたは別のタイプを選択します
std::conditional
テンプレート<ブール B、クラス T、クラス F > |
(C++11以降) |
はメンバー typedef type
を提供します。コンパイル時に B
が true の場合、または a> として定義されます。 が false の場合、T
B
F
メンバータイプ
メンバータイプ | 意味 |
type |
B == true の場合は T 、B == false の場合は F |
補助タイプ
テンプレート< bool B、クラス T、クラス F > |
(C++14以降) |
可能な実装
template<bool B, class T, class F>
struct conditional { typedef T type; };
template<class T, class F>
struct conditional<false, T, F> { typedef F type; };
通話例
#include <iostream>
#include <type_traits>
#include <typeinfo>
struct A
{
};
struct B
{
};
int main()
{
typedef std::conditional<true, int, double>::type Type1;
typedef std::conditional<false, int, double>::type Type2;
typedef std::conditional<sizeof(int) >= sizeof(double), int, double >::type Type3;
typedef std::conditional<false, A, B>::type Type4;
typedef std::conditional<true, std::string, char*>::type Type5;
std::cout << "std::conditional<true, int, double>::type: "
<< typeid(Type1).name() << std::endl;
std::cout << "std::conditional<false, int, double>::type: "
<< typeid(Type2).name() << std::endl;
std::cout << "std::conditional<sizeof(int)>=sizeof(double),int,double>::type:"
<< typeid(Type3).name() << std::endl;
std::cout << "std::conditional<false, A, B>::type: "
<< typeid(Type4).name() << std::endl;
std::cout << "std::conditional<true, std::string, char*>::type: "
<< typeid(Type5).name() << std::endl;
return 0;
}
出力
std::conditional<true, int, double>::type: i
std::conditional<false, int, double>::type: d
std::conditional<sizeof(int)>=sizeof(double),int,double>::type:d
std::conditional<false, A, B>::type: 1B
std::conditional<true, std::string, char*>::type: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE