[英]Do C++ Concepts allow for my class at declaration/definition to specify it satisfies certain concept?
Currently best way I can think of is to use static_assert, but I would prefer nicer way. 目前我能想到的最好的方法是使用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()
{
}
Currently no, the keyword you would be looking for to do that would be requires
From cppreference 目前没有,您要寻找的关键字
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.关键字
requires
以两种方式使用:1)引入一个requires子句,它指定模板参数或函数声明的约束。
Since you are not dealing with a function declaration, this is irrelevant. 由于您没有处理函数声明,因此这是无关紧要的。 The second case is
第二种情况是
To begin a requires-expression, which is a prvalue expression of type bool that describes the constraints on some template arguments.
要开始一个requires-expression,它是bool类型的prvalue表达式,用于描述某些模板参数的约束。 Such expression is true if the corresponding concept is satisfied, and false otherwise:
如果满足相应的概念,则表达式为true,否则为false:
Which is not relevent here again because you are not trying to validate a constraint on some template arguments 由于您没有尝试验证某些模板参数的约束,因此这里不再相关
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.