概念——如何约束积分模板值

Concepts - how to constrain integral template value

模板定义如下:

template<size_t N>
void foo( void ) {
  /* ... */
}

如何定义一个概念使得N必须是非零正值(N >= 1)?

类似于:

template<size_t N>
concept NonZeroSize = /* to be implemented, N>=1 */

template<NonZeroSize N>
void foo( void ) {
  /* Do whatever only if N >= 1 */
}

谢谢!

像这样:

template <size_t N> requires NonZeroSize<N>
void foo();

或者只是:

template <size_t N> requires (N > 0)
void foo();

简洁的形式是为类型概念保留的。


概念定义本身只是一个任意的布尔表达式:

template <size_t N>
concept NonZeroSize = (N > 0);

requires-expression只是一种特殊的表达方式,在定义概念时非常有用,但它既没有用于所有概念定义,也[=24] =]必须 它首先出现在概念定义中。这些东西是正交的。