我正在学习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;
}
2条答案
按热度按时间e37o9pze1#
没有必要为您的概念使用
requires
-子句,因为它通常用于检查表达式的有效性。只是简单地因为
copy_constructible
已经保证了move_constructible
。如果您还需要类型是可复制分配的,则会更容易mzmfm0qo2#
event
concept
需要更多requires
: