我有一些型別特征SomeTraits,我可以從中提取型別是否T滿足某些條件,通過SomeTraits<T>::value. 如何檢查給定的所有型別std::tuple<>并檢查(通過靜態斷言)它們是否都滿足上述條件?例如
using MyTypes = std::tuple<T1, T2, T3>;
// Need some way to do something like
static_assert(SomeTupleTraits<MyTypes>::value, "MyTypes must be a tuple that blabla...");
在哪里SomeTupleTraits會檢查是否SomeTraits<T>::value == true為每個型別里面MyTypes?
我僅限于 C 14。
uj5u.com熱心網友回復:
作為一個班輪(可選換行符),您可以執行以下操作:
// (c 20)
static_assert([]<typename... T>(std::type_identity<std::tuple<T...>>) {
return (SomeTrait<T>::value && ...);
}(std::type_identity<MyTypes>{}));
或者你可以創建一個輔助特征來做到這一點:
// (c 17)
template<template<typename, typename...> class Trait, typename Tuple>
struct all_of;
template<template<typename, typename...> class Trait, typename... Types>
struct all_of<Trait, std::tuple<Types...>> : std::conjunction<Trait<Types>...> {};
static_assert(all_of<SomeTrait, MyTypes>::value);
或者在 C 11 中,您可以std::conjunction在 helper trait 中重新實作:
template<template<typename, typename...> class Trait, typename Tuple>
struct all_of;
template<template<typename, typename...> class Trait>
struct all_of<Trait, std::tuple<>> : std::true_type {};
template<template<typename, typename...> class Trait, typename First, typename... Rest>
struct all_of<Trait, std::tuple<First, Rest...>> :
std::conditional<bool(Trait<First>::value),
all_of<Trait, std::tuple<Rest...>>,
std::false_type>::type::type {};
static_assert(all_of<SomeTrait, MyTypes>::value, "");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477231.html
