小编Kan*_*ame的帖子

C++20 要求表达式未捕获 static_assert

当我第一次听说 C++20 约束和概念时,我真的很兴奋,到目前为止,我对它们进行了很多有趣的测试。最近,我想看看是否可以使用 C++20 概念来测试类或函数的约束。例如:

template <int N>
requires (N > 0)
class MyArray { ... };

template <int N>
concept my_array_compiles = requires {
  typename MyArray<N>;
};

my_array_compiles<1>;  // true
my_array_compiles<0>;  // false
Run Code Online (Sandbox Code Playgroud)

起初我没有遇到任何问题,但我遇到了一种情况,依赖函数中的 static_assert 会阻止编译,即使它出现在需要表达式中。下面是一个例子来说明这一点:

template <bool b>
requires b
struct TestA {
  void foo() {}
};

template <bool b>
struct TestB {
  static_assert(b);
  void foo() {}
};

template <template<bool> class T, bool b>
concept can_foo = requires (T<b> test) {
  test.foo();
};

can_foo<TestA, true>;   // true
can_foo<TestA, …
Run Code Online (Sandbox Code Playgroud)

c++ templates type-constraints c++-concepts c++20

5
推荐指数
1
解决办法
962
查看次数

标签 统计

c++ ×1

c++-concepts ×1

c++20 ×1

templates ×1

type-constraints ×1