【发布时间】:2019-09-01 19:21:16
【问题描述】:
我开始学习 C++20 的概念。我想为 typelist 的过滤谓词创建一个concept。
假设,有一个这样定义的类型列表:
template <typename ...TYPE>
struct List {
};
还有Filter,它可以根据谓词过滤类型列表。一个可能的定义是这样的:
template <template <typename> typename PREDICATE, typename LIST>
struct Filter {
using result = List<...>; // some implementation here
};
这意味着,对于每个LIST 的TYPE 参数,必须评估PREDICATE<TYPE>::value(它是一个bool 值),如果它是true,那么Filter::result 必须包含@987654332 @。
现在,我如何为PREDICATE 创建一个concept,所以Filter 将只接受它,如果它包含一个value 成员(对于所有TYPE 专业化,它在LIST 中) ?
我的意思是,对于这个MyPredicate,concept 应该只允许用LIST 实例化Filter,除了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
【问题讨论】:
-
List中是否只有一个元素评估为 true? -
@0x499602D2:不,可以是任何东西
-
This answer 与您要查找的内容接近。