c++ - 如何为类型列表谓词创建 C++20 概念?

标签 c++ c++20

我开始学习 C++20 的概念。我想创建一个 concept用于类型列表的过滤谓词。

假设,有一个这样定义的类型列表:

template <typename ...TYPE>
struct List {
};

还有 Filter ,它可以根据谓词过滤类型列表。一个可能的定义是这样的:

template <template <typename> typename PREDICATE, typename LIST>
struct Filter {
    using result = List<...>; // some implementation here
};

这意味着,对于每个 LISTTYPE参数,PREDICATE<TYPE>::value必须评估(它是一个 bool 值),如果它是 true , 然后 Filter::result必须包含 TYPE .

现在,我如何创建 concept对于 PREDICATE , 所以 Filter只会接受它,如果它包含 value成员(对于所有 TYPE 专业,在 LIST 中)?

我的意思是,对于这个 MyPredicate , concept应该只允许实例化 FilterLIST , 除 some_type1 外没有其他类型和 some_type2 :

template <typename TYPE>
struct MyPredicate;

template <>
struct MyPredicate<some_type1> {
    static constexpr bool value = true;
};

template <>
struct MyPredicate<some_type2> {
    static constexpr bool value = false;
};

Filter<MyPredicate, List<some_type1, some_type2>>::result x; // here, x should have the type List<some_type1>
Filter<MyPredicate, List<int>>::result y; // should not compile, as MyPredicate<int> isn't defined

最佳答案

您有一个检查单个实例化的概念:

template <typename T>
concept nested_value = std::same_as<decltype(T::value), bool>;

您可以在折叠表达式中使用:

template <template <typename> class Pred, typename List>
struct Filter;

template <template <typename> class Pred, template <typename...> class L, typename... Ts>
    requires (nested_value<Pred<Ts>> && ... )
struct Filter<Pred, L<Ts...>> {
    // ...
};

或者你基本上可以在一个概念中做同样的事情:

template <template <typename> class Pred, typename List>
struct all_nested_impl : std::false_type { };

template <template <typename> class Pred, template <typename...> class L, typename... Ts>
struct all_nested_impl<Pred, L<Ts...>>
    : std::bool_constant<(nested_value<Pred<Ts>> && ...)>
{ };

template <template <typename> class Pred, typename List>
concept all_nested = all_nested_impl<Pred, List>::value;

template <template <typename> class Pred, typename List>
    requires all_nested<Pred, List>
struct Filter;

或者如果你只是翻转参数,你就可以写:

template <template <typename> class Pred, all_nested<Pred> List>
struct Filter;

关于c++ - 如何为类型列表谓词创建 C++20 概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57748818/

相关文章:

c++ - 检查所有 __m128i 组件是否为 0 的最有效方法 [使用 <= SSE4.1 内在函数]

c++ - Qt 图像处理应用程序需要直方图小部件

c++ - p2p 开源库 tcp/udp 组播支持

c++ - 在 C++20 中,如果宏是 #undef'd,然后又是 #define'd,那么它是否被认为是 "active"?

c++ - 将空基类优化对象转换为另一种类型会破坏严格的别名吗?

c++ - 类似于 `declval` 的概念

派生类的 C++ 构造函数,其中基类包含类成员

c++ - 位操作,置换位

c++ - shift_right() 在 C++20 中如何实现?

c++ - 即使在 C++20 中 std::memcpy 也不是 constexpr 的原因是什么?