我正在学习concepts
C++ 20,并提出需要concept
使用先前定义的concept
.
因此,在下面的示例中,我预计f<pub_b>()
会生成编译器错误,因为events_published
inpub_b
不满足publisher
概念,因为ev_2
不满足event
概念。
看来在概念event
中使用概念publisher
并没有什么效果。
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;
}
无需
requires
为您的概念使用 - 子句,因为它通常用于检查表达式的有效性。只是简单地正如
copy_constructible
已经保证的那样move_constructible
。如果您还需要可复制分配的类型,生活会更容易需要
event
concept
更多requires
: