gpt4 book ai didi

c++ - C++ 概念是否允许我的类在声明/定义时指定它满足特定概念?

转载 作者:可可西里 更新时间:2023-11-01 15:23:53 24 4
gpt4 key购买 nike

目前我能想到的最好的方法是使用 static_assert,但我更喜欢更好的方法。

#include <set>
#include <forward_list>

using namespace std;

template<typename C>
concept bool SizedContainer = requires (C c){
c.begin();
c.end();
{c.size()} -> size_t;
};

static_assert(SizedContainer<std::set<int>>);
static_assert(!SizedContainer<std::forward_list<int>>);
static_assert(!SizedContainer<float>);

class MyContainer{
public:
void begin(){};
void end(){};
size_t size(){return 42;};
};

static_assert(SizedContainer<MyContainer>);



int main()
{
}

最佳答案

目前没有,您要寻找的关键字是 requires来自 cppreference

The keyword requires is used in two ways: 1) To introduce a requires-clause, which specifies constraints on template arguments or on a function declaration.

因为您不是在处理函数声明,所以这是无关紧要的。第二种情况是

To begin a requires-expression, which is a prvalue expression of type bool that describes the constraints on some template arguments. Such expression is true if the corresponding concept is satisfied, and false otherwise:

这在这里又不相关,因为您没有尝试验证对某些模板参数的约束

关于c++ - C++ 概念是否允许我的类在声明/定义时指定它满足特定概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48189572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com