c++ 概念可以用来对值和类型施加约束吗?

k5ifujac  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(141)

Concepts可用于将类型约束作为模板参数,如下例所示:

  1. template<typename t, int v>
  2. concept the_concept1 = sizeof(t) > v;
  3. template<int v, the_concept1<v> t>
  4. struct some_struct1{};

字符串
我尝试使用类似的方法,其值如下例所示:

  1. template<int v1, int v2>
  2. concept the_concept2 = v1 > v2;
  3. template<int v1, the_concept2<v1> v2>
  4. struct some_struct2{};


但是在G++ 10中,我得到了以下错误消息:

  1. error: the_concept2 does not constrain a type


所以我想知道概念是否可以用来约束价值观?如果可以的话,我应该怎么做?
编辑:我的最终目标是在 declaration 中使用带有可变模板参数的模板结构的概念,如:

  1. template<typename t, std::size_t ... v>
  2. struct the_struct;


我需要一个概念来检查 everyv是否小于sizeof(t)

sgtfey8w

sgtfey8w1#

如果你想使用一个概念作为模板参数的命名 type 约束,就像你的例子一样,这个概念需要应用到一个 type 模板参数。
你仍然可以定义仅适用于非类型模板参数的概念,但是,只要你在允许这些的上下文中使用它;例如使用requires-clause:

  1. template<int v1, int v2>
  2. concept the_concept2 = v1 > v2;
  3. template<int v1, int v2> requires the_concept2<v1, v2>
  4. struct some_struct2{};
  5. using valid = some_struct2<42, 41>;
  6. //using invalid = some_struct2<42, 42>; // constraints not satisfied

字符串
另一个应用于函数模板或类模板的成员函数的示例:

  1. template<int v1, int v2>
  2. concept the_concept2 = v1 > v2;
  3. template <int a, int b>
  4. void bar() requires the_concept2<a, b> {}
  5. template <int a, int b>
  6. struct Foo {
  7. static void bar() requires the_concept2<a, b> {}
  8. };
  9. int main() {
  10. bar<2, 1>();
  11. Foo<2, 1>::bar();
  12. //bar<2, 2>(); // candidate template ignored: constraints not satisfied
  13. //Foo<2, 2>::bar(); // invalid reference to function 'bar': constraints not satisfied
  14. }


下面的OP编辑(基本上问了一个完全不同的问题)
编辑:我的最终目标是在声明一个带有可变模板参数的模板结构时使用这个概念,比如:

  1. template<typename t, std::size_t ... v>
  2. struct the_struct;


我需要一个概念来检查是否每个v都小于sizeof(t)
可以通过指定概念本身来实现,以应用于在sizeof(T) > v检查中使用参数包扩展进行扩展的可变参数非类型模板参数:

  1. #include <cstddef>
  2. #include <cstdint>
  3. template<typename T, std::size_t... v>
  4. concept the_concept1 = (... && (sizeof(T) > v));
  5. template<typename T, std::size_t... vs> requires the_concept1<T, vs...>
  6. struct the_struct;
  7. using TypeOfSize4Bytes = uint32_t;
  8. using valid = the_struct<TypeOfSize4Bytes, 1, 3, 2, 1>;
  9. using also_valid = the_struct<TypeOfSize4Bytes>;
  10. //using invalid = the_struct<TypeOfSize4Bytes, 1, 2, 4>; // error: constraints not satisfied

展开查看全部

相关问题