【问题标题】:How to apply concepts to member variables如何将概念应用于成员变量
【发布时间】:2018-04-25 09:19:15
【问题描述】:

我目前正在编写我的第一个概念。编译器是使用 -fconcepts 调用的 g++ 7.2。我的概念是这样的:

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 }
    };
};

如您所见,Environment 应该有一个名为 stack 的成员。该成员应与 Stack 的概念相匹配。如何将这样的要求添加到环境中?

【问题讨论】:

    标签: c++ g++ require c++-concepts c++20


    【解决方案1】:

    我使用 gcc 6.3.0 和 -fconcepts 选项测试了这个解决方案。

    #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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      相关资源
      最近更新 更多