cppreference.com 指出:
概念不能递归地引用自己
Concepts cannot recursively refer to themselves
但是我们如何定义一个概念来表示整数或整数向量,或整数向量的向量等.
But how can we define a concept that will represent an integer or a vector of integers, or a vector of vector of integers, etc.
我可以拥有这样的东西:
I can have something this:
template < typename Type > concept bool IInt0 = std::is_integral_v<Type>;
template < typename Type > concept bool IInt1 = IInt0<Type> || requires(Type tt) { {*std::begin(tt)} -> IInt0; };
template < typename Type > concept bool IInt2 = IInt1<Type> || requires(Type tt) { {*std::begin(tt)} -> IInt1; };
static_assert(IInt2<int>);
static_assert(IInt2<std::vector<int>>);
static_assert(IInt2<std::vector<std::vector<int>>>);
但我想要像 IIntX 这样的东西,这意味着任何 N 的 IIntN.
But I want to have something like IIntX that will mean IIntN for any N.
有可能吗?
概念总是可以遵从类型特征:
Concepts can always defer to a type trait:
template <typename T> concept C = some_trait<T>::value;
而且这个特征可以递归:
And that trait can be recursive:
template <typename T>
struct some_trait : std::false_type { };
template <std::Integral T>
struct some_trait<T> : std::true_type { };
template <typename T, typename A>
struct some_trait<std::vector<T, A>> : some_trait<T> { };
如果你的意思不只是vector,那么最后的部分特化可以推广为:
If you don't mean just vector, then the last partial specialization can be generalized to:
template <std::Range R>
struct some_trait<R> : some_trait<std::range_value_t<R>> { };
这篇关于如何定义递归概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
当没有异常时,C++ 异常会以何种方式减慢代码速In what ways do C++ exceptions slow down code when there are no exceptions thown?(当没有异常时,C++ 异常会以何种方式减慢代码速度?)
为什么要捕获异常作为对 const 的引用?Why catch an exception as reference-to-const?(为什么要捕获异常作为对 const 的引用?)
我应该何时以及如何使用异常处理?When and how should I use exception handling?(我应该何时以及如何使用异常处理?)
C++中异常对象的范围Scope of exception object in C++(C++中异常对象的范围)
从构造函数的初始化列表中捕获异常Catching exceptions from a constructor#39;s initializer list(从构造函数的初始化列表中捕获异常)
C++03 throw() 说明符 C++11 noexcept 之间的区别Difference between C++03 throw() specifier C++11 noexcept(C++03 throw() 说明符 C++11 noexcept 之间的区别)