如何在C++ 20中定义一个使用"concept“的”concept“?

vaj7vani  于 2023-10-20  发布在  其他
关注(0)|答案(2)|浏览(104)

我正在学习C++ 20中的concepts,并且需要使用以前定义的concept定义concept
因此,在下面的例子中,我预计f<pub_b>()会生成编译器错误,因为pub_b中的events_published不满足publisher概念,因为ev_2不满足event概念。
publisher概念中使用event概念似乎没有效果。
g++ version报告

g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我做错了什么?

#include <concepts>
#include <tuple>

template <typename t>
concept event = requires {
  std::default_initializable<t>;
  std::copy_constructible<t>;
  std::move_constructible<t>;
};

struct ev_1 {
  ev_1() = default;
  ev_1(const ev_1 &) = default;
  ev_1(ev_1 &&) = default;
};

struct ev_2 {
  ev_2() = delete;
  ev_2(const ev_2 &) = default;
  ev_2(ev_2 &&) = default;
};

template <typename t>
concept publisher = requires {
  typename t::events_published;

  requires[]<std::size_t... t_idx>(std::index_sequence<t_idx...>) {
    return ((event<typename std::tuple_element_t<
                 t_idx, typename t::events_published>>)&&...);
  }
  (std::make_index_sequence<std::tuple_size_v<typename t::events_published>>());
};

struct pub_a {
  using events_published = std::tuple<ev_1>;
};

struct pub_b {
  using events_published = std::tuple<ev_2>;
};

template <publisher t_publisher> void f() {}

int main() {
  f<pub_a>();

  f<pub_b>();

  return 0;
}
e37o9pze

e37o9pze1#

没有必要为您的概念使用requires-子句,因为它通常用于检查表达式的有效性。只是简单地

#include <concepts>

template <typename t>
concept event = std::default_initializable<t> &&
                std::copy_constructible<t>;

因为copy_constructible已经保证了move_constructible。如果您还需要类型是可复制分配的,则会更容易

template <typename t>
concept event = std::semiregular<t>;
mzmfm0qo

mzmfm0qo2#

eventconcept需要更多requires

template <typename t>
concept event = requires {
    requires std::default_initializable<t>;
    requires std::copy_constructible<t>;
    requires std::move_constructible<t>;
};
int main() {
    f<pub_a>();

    //f<pub_b>(); // Now gives a compilation error
}

相关问题