std::disjunction
| ヘッダ <type_traits> で定義
|
||
template<class... B> struct disjunction; |
(1) | (C++17以上) |
型特性 B... の論理和を形成します。 実質的に特性の並びの OR を行います。
特殊化 std::disjunction<B1, ..., BN> は以下のようなパブリックな曖昧でない基底を持ちます。
sizeof...(B) == 0であればstd::false_type、そうでなければB1, ..., BN内のbool(Bi::value) == trueである最初の型Bi、またはそのような型が存在しない場合はBN。
disjunction と operator= 以外の基底クラスのメンバ名は隠蔽されておらず、 disjunction 内で曖昧さなく利用可能です。
論理和は短絡評価です。 bool(Bi::value) != false であるテンプレート型引数 Bi が存在する場合、 disjunction<B1, ..., BN>::value の実体化は j > i に対する Bj::value の実体化を要求しません。
テンプレート引数
| B... | - | Bi::value が実体化されるすべてのテンプレート引数 Bi は基底クラスとして使用可能でなければならず、 bool に変換可能なメンバ value を定義しなければなりません。
|
ヘルパー変数テンプレート
<tbody> </tbody> template<class... B> inline constexpr bool disjunction_v = disjunction<B...>::value; |
(C++17以上) | |
実装例
template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
: std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };
|
ノート
disjunction の特殊化は必ずしも std::true_type や std::false_type を継承するとは限りません。 単純に、明示的に bool に変換されたとき false である ::value を持つ最初の B を、または、それらがすべて false に変換されるときは一番最後の B を継承します。 例えば、 std::disjunction<std::integral_constant<int, 2>, std::integral_constant<int, 4>>::value は 2 です。
短絡評価の実体化は disjunction が畳み込み式と異なるところです。 (... || Bs::value) のような畳み込み式は Bs 内のすべての B を実体化しますが、 std::disjunction_v<Bs...> はいったん値が決定されれば実体化を停止します。 これは後ろの型が実体化するのに高価であるか、間違った型で実体化したときに難しいエラーが発生する場合に、特に役に立ちます。
例
#include <type_traits>
#include <string>
// checking if Foo is constructible from double will cause a hard error
struct Foo {
template<class T>
struct sfinae_unfriendly_check { static_assert(!std::is_same_v<T, double>); };
template<class T>
Foo(T, sfinae_unfriendly_check<T> = {} );
};
template<class... Ts>
struct first_constructible {
template<class T, class...Args>
struct is_constructible_x : std::is_constructible<T, Args...> {
using type = T;
};
struct fallback {
static constexpr bool value = true;
using type = void; // type to return if nothing is found
};
template<class... Args>
using with = typename std::disjunction<is_constructible_x<Ts, Args...>...,
fallback>::type;
};
// OK, is_constructible<Foo, double> not instantiated
static_assert(std::is_same_v<first_constructible<std::string, int, Foo>::with<double>,
int>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<>, std::string>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<const char*>,
std::string>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<void*>, void>);
int main() { }
関連項目
(C++17) |
論理否定メタ関数 (クラステンプレート) |
(C++17) |
可変個引数の論理積メタ関数 (クラステンプレート) |