C++ 概念是否允许我的 class 在 declaration/definition 指定它满足特定概念?
Do C++ Concepts allow for my class at declaration/definition to specify it satisfies certain concept?
目前我能想到的最好的方法是使用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:
这里又不相关,因为您没有尝试验证某些模板参数的约束
目前我能想到的最好的方法是使用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:
这里又不相关,因为您没有尝试验证某些模板参数的约束