c++g++c++20c++-conceptsrequires-expression

How to apply concepts to member variables


I'm currently writing my first concepts. Compiler is g++ 7.2 invoked with -fconcepts. My concepts look like this:

template <typename stack_t>
concept bool Stack() {
    return requires(stack_t p_stack, size_t p_i) {
        { p_stack[p_i] };
    };
};

template <typename environment_t>
concept bool Environment() {
    return requires(environment_t p_env) {
        { p_env.stack }
    };
};

As you can see Environment should have a member named stack. This member should match the concept Stack. How do I add such a requirement to Environment?


Solution

  • I tested this solution with gcc 6.3.0 and -fconcepts option.

    #include <iostream>
    #include <vector>
    
    template <typename stack_t>
    concept bool Stack() {
        return requires(stack_t p_stack, size_t p_i) {
            { p_stack[p_i] };
        };
    };
    
    template <typename environment_t>
    concept bool Environment() {
        return requires(environment_t p_env) {
            { p_env.stack } -> Stack; //here
        };
    };
    
    struct GoodType
    {
      std::vector<int> stack;
    };
    
    struct BadType
    {
      int stack;
    };
    
    template<Environment E>
    void test(E){}
    
    int main()
    {
      GoodType a;
      test(a); //compiles fine
    
      BadType b;
      test(b); //comment this line, otherwise build fails due to constraints not satisfied
    
      return 0;
    }