如何将概念应用于成员变量

问题描述 投票:3回答:1

我正在写我的第一个概念。编译器是使用-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个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.