使用 require 子句仅有条件地存在成员变量
我希望使 dat
中 member
的存在依赖于 B
(或其他一些概念)。
template <bool B>
struct dat {
void member_func() requires (B) {} //ok
std::byte member requires (B); //err
};
我知道这可能与专业化有关,但据我所知,如果需要多个不同的成员要求,那会变得非常难看。
如果没有专业化,这种行为是否可能?
I wish to make the existence of member
within dat
dependent on B
(or some other concept).
template <bool B>
struct dat {
void member_func() requires (B) {} //ok
std::byte member requires (B); //err
};
I know this is possible to do with specialisation but as far as I am aware that would get very ugly if multiple different member requirements were nessacary.
Is this behaviour possible without specialisation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几种方法可以实现此目的(请参阅条件成员)。
一种是使用条件来更改
member
的类型:这并不是真正的条件成员变量,
member
始终存在。但有时它是您关心的类型,有时它是不占用空间的空类型。这可能已经足够好了 - 如果您实际上不需要访问该事物,并且没有代码依赖于该成员的存在。如果这不起作用,那么你就必须求助于不同类型的专业化。但您不必专门化所有
dat
,只需有条件地提供此成员的基类即可:这里,
dat
有一个名为member 的成员
但dat
没有数据成员。这对于像iterator_category
(正如我提到的)。两者都不是很好的解决方案,但两者都绝对胜过仅仅为了以成员变量为条件而专门化整个类。如果需要多个不同的、独立的条件变量,则两者都会缩放。
There's a couple approaches to this (see Conditional Members).
One is you use the condition to change the type of
member
:This isn't really a conditional member variable,
member
is always present. But it's sometimes the type you care about and other times it's an empty type that takes no space. That could be good enough - if you never actually have to access the thing, and no code depends on the presence of this member.If that doesn't work, then you do have to resort to a different sort of specialization. But you don't have to specialize all of
dat
, just a base class that conditionally provides this member:Here,
dat<true>
has a member namedmember
butdat<false>
has no data members. Which is important for things likeiterator_category
(as I mention).Neither are great solutions, but both definitely beat having to specialize the entire class just to condition on member variable. Both scale if there is a need to have multiple different, independently conditional variables.