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

2023-12-30

概念可用于对类型进行约束作为模板参数,如下例所示:

template<typename t, int v>
concept the_concept1 = sizeof(t) > v;

template<int v, the_concept1<v> t>
struct some_struct1{};

我正在尝试使用类似的方法,其值如下例所示:

template<int v1, int v2>
concept the_concept2 = v1 > v2;

template<int v1, the_concept2<v1> v2>
struct some_struct2{};

但使用 G++ 10 我收到以下错误消息:

error: ‘the_concept2’ does not constrain a type

所以我想知道是否可以用概念来约束价值观?如果是这样那我该怎么办呢?

编辑:我的最终目标是使用这个概念宣言具有可变模板参数的模板结构,例如:

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

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


如果你想使用一个概念作为命名type对模板参数的约束,如您的示例中所示,该概念需要应用于type模板参数。

您仍然可以定义仅适用于例如但是,只要您在允许这些参数的上下文中使用它,就可以使用非类型模板参数;例如使用require子句:

template<int v1, int v2>
concept the_concept2 = v1 > v2;

template<int v1, int v2> requires the_concept2<v1, v2>
struct some_struct2{};

using valid = some_struct2<42, 41>;
//using invalid = some_struct2<42, 42>; // constraints not satisfied

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

template<int v1, int v2>
concept the_concept2 = v1 > v2;

template <int a, int b>
void bar() requires the_concept2<a, b> {} 

template <int a, int b>
struct Foo {
    static void bar() requires the_concept2<a, b> {} 
};

int main() {
    bar<2, 1>();
    Foo<2, 1>::bar();
    //bar<2, 2>();      // candidate template ignored: constraints not satisfied
    //Foo<2, 2>::bar(); // invalid reference to function 'bar': constraints not satisfied
}

以下OP编辑(基本上问了一个完全不同的问题)

编辑:我的最终目标是在模板声明中使用这个概念 具有可变模板参数的结构,例如:

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

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

可以通过指定概念本身来应用可变参数非类型模板参数来实现,这些参数在sizeof(T) > v使用参数包扩展检查:

#include <cstddef>
#include <cstdint>

template<typename T, std::size_t... v>
concept the_concept1 = (... && (sizeof(T) > v));

template<typename T, std::size_t... vs> requires the_concept1<T, vs...>
struct the_struct;

using TypeOfSize4Bytes = uint32_t;

using valid = the_struct<TypeOfSize4Bytes, 1, 3, 2, 1>;
using also_valid = the_struct<TypeOfSize4Bytes>;
//using invalid = the_struct<TypeOfSize4Bytes, 1, 2, 4>;  // error: constraints not satisfied
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

概念可以用来对值和类型施加约束吗? 的相关文章

随机推荐