【发布时间】:2021-06-12 07:22:43
【问题描述】:
现在可以使用 C++20 编写模板函数 detect_foo,它将返回模板参数是否是具有名为 foo 的成员的结构。
例子:
consteval bool detect_foo(auto&& arg) {
if constexpr(requires { arg.foo; }) {
// arg has a "foo" member
return true;
} else {
// arg does not
return false;
}
}
因此,我们在. 运算符的左侧有泛型:在arg.foo 中,arg 可以是泛型的。
我的问题是:foo 部分如何成为通用的,例如我们是否有一种非宏方法来编写一个detect 函数,该函数的 API 与此相距不远:
bool has_the_member = detect(some_struct, name_of_a_member);
例如
struct foo { int value; } a_foo;
struct bar { int value; } a_bar;
detect(a_foo, /* some magic incantation to refer to "value" */);
detect(a_bar, /* should be the same incantation than for a_foo */);
【问题讨论】:
-
这是不可能的,我不确定你为什么需要它。您可以只使用
requires,而不用将其包装在函数中。 -
constexpr auto has_the_member = requires { some_struct.name_of_a_member; }; -
@HolyBlackCat 我关于成员是否在这里的实际业务逻辑比真/假更复杂,我不想为每个成员重复它(例如 N 类型,@987654334 @、
Bar、Baz、可能有 M 个可选字段、name、value、min、max- 我想对type ⨯ field产品的每种情况执行相同的逻辑,并且仅编写一次该逻辑,而不是每个字段一次) -
我建议将此添加到问题中。
-
那将违背sscce.org
标签: c++ c++20 c++-concepts