Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

#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()
{
}
like image 669
NoSenseEtAl Avatar asked Jan 10 '18 14:01

NoSenseEtAl


1 Answers

Currently no, the keyword you would be looking for to do that would be requires From 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.

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. Such expression is true if the corresponding concept is satisfied, and false otherwise:

Which is not relevent here again because you are not trying to validate a constraint on some template arguments

like image 197
Pumkko Avatar answered Nov 09 '22 13:11

Pumkko