std::is_same
From cppreference.com
| ヘッダ <type_traits> で定義 |
||
| template< class T, class U > struct is_same; |
(C++11以降) | |
もし T と U が同じ型(const/volatile 修飾を考慮に入れて)を指す場合、メンバ定数 value が true となります。そうでない場合、value は false となります。
交換法則が満たされます。つまり、任意の2つの型 T と U について、is_same<T, U>::value == true であるのは、is_same<U, T>::value == true である場合のみです。
プログラムが std::is_same または std::is_same_v(C++17以降) に特殊化を追加すると、動作は未定義です。
目次 |
[編集] ヘルパー変数テンプレート
| template< class T, class U > constexpr bool is_same_v = is_same<T, U>::value; |
(C++17以降) | |
std::integral_constant から継承
メンバ定数
| value [static] |
T と U が同じ型であれば true、そうでなければ false(公開静的メンバ定数) |
メンバ関数
| operator bool |
オブジェクトを bool に変換し、value を返します。 (public member function) |
| operator() (C++14) |
value を返します。 (public member function) |
メンバ型
| 型 | 定義 |
value_type
|
bool |
type
|
std::integral_constant<bool, value> |
[編集] 可能な実装
template<class T, class U> struct is_same : std::false_type {}; template<class T> struct is_same<T, T> : std::true_type {}; |
[編集] 例
このコードを実行
#include <cstdint> #include <iostream> #include <type_traits> int main() { std::cout << std::boolalpha; // some implementation-defined facts // usually true if 'int' is 32 bit std::cout << std::is_same<int, std::int32_t>::value << ' '; // maybe true // possibly true if ILP64 data model is used std::cout << std::is_same<int, std::int64_t>::value << ' '; // maybe false // same tests as above, except using C++17's std::is_same_v<T, U> format std::cout << std::is_same_v<int, std::int32_t> << ' '; // maybe true std::cout << std::is_same_v<int, std::int64_t> << '\n'; // maybe false // compare the types of a couple variables long double num1 = 1.0; long double num2 = 2.0; static_assert( std::is_same_v<decltype(num1), decltype(num2)> == true ); // 'float' is never an integral type static_assert( std::is_same<float, std::int32_t>::value == false ); // 'int' is implicitly 'signed' static_assert( std::is_same_v<int, int> == true ); static_assert( std::is_same_v<int, unsigned int> == false ); static_assert( std::is_same_v<int, signed int> == true ); // unlike other types, 'char' is neither 'unsigned' nor 'signed' static_assert( std::is_same_v<char, char> == true ); static_assert( std::is_same_v<char, unsigned char> == false ); static_assert( std::is_same_v<char, signed char> == false ); // const-qualified type T is not same as non-const T static_assert( !std::is_same<const int, int>() ); }
実行結果の例
true false true false
[編集] 関連項目
| (C++20) |
型が別の型と同一であることを規定する (コンセプト) |
decltype 指定子(C++11) |
式またはエンティティの型を取得します |