C ++ std :: variant vs std :: any [英] C++ std::variant vs std::any
问题描述
C ++ 17表示 std :: variant
和 std :: any
都可以在对象下存储不同类型的值.对我来说,它们在某种程度上是相似的(是吗?).
C++17 presents std::variant
and std::any
, both able to store different type of values under an object. For me, they are somehow similar (are they?).
此外, std :: variant
限制了该条目的类型.为什么我们更喜欢使用 std :: variant
而不是 std :: any
?
Also std::variant
restricts the entry types, beside this one. Why we should prefer std::variant
over std::any
which is simpler to use?
推荐答案
在编译时检查的内容越多,运行时的错误就越少.
variant
保证它包含一种类型列表(加上无值的异常).它为您提供了一种保证使用它的代码使用 std :: visit
来考虑变体中每种情况的方法;甚至是 variant
s(或更多)的对对的所有情况.
variant
guarantees that it contains one of a list of types (plus valueless by exception). It provides a way for you to guarantee that code operating on it considers every case in the variant with std::visit
; even every case for a pair of variant
s (or more).
任何
不包含.使用 any
,最好的办法是如果类型不完全符合我的要求,则某些代码将无法运行".
any
does not. With any
the best you can do is "if the type isn't exactly what I ask for, some code won't run".
变体
存在于自动存储中. any
可以使用免费商店;这意味着 any
具有性能,而 noexcept(false)
问题却没有 variant
.
variant
exists in automatic storage. any
may use the free store; this means any
has performance and noexcept(false)
issues that variant
does not.
对于 any
,检查其中N种类型为O(N)-对于 variant
,其值为O(1).
Checking for which of N types is in it is O(N) for an any
-- for variant
it is O(1).
any
是已修饰的 void *
. variant
是经过修饰的 union
.
any
is a dressed-up void*
. variant
is a dressed-up union
.
任何
无法存储不可复制或不可移动的类型. variant
可以.
any
cannot store non-copy or non-move able types. variant
can.
variant
的类型是代码阅读者的文档.
The type of variant
is documentation for the reader of your code.
通过API传递 variant< Msg1,Msg2,Msg3>
使操作显而易见;在其中传递 any
意味着理解API需要可靠的文档或阅读实现源.
Passing a variant<Msg1, Msg2, Msg3>
through an API makes the operation obvious; passing an any
there means understanding the API requires reliable documentation or reading the implementation source.
任何对静态无类型语言感到沮丧的人都会理解 any
的危险.
Anyone who has been frustrated by statically typeless languages will understand the dangers of any
.
现在,这并不意味着 any
是不好的;它只是不能解决与 variant
相同的问题.作为用于类型擦除目的的可复制对象,它可能很棒.运行时动态类型具有它的位置;但是那个地方不是无处不在",而是你无法避免的地方".
Now this doesn't mean any
is bad; it just doesn't solve the same problems as variant
. As a copyable object for type erasure purposes, it can be great. Runtime dynamic typing has its place; but that place is not "everywhere" but rather "where you cannot avoid it".
这篇关于C ++ std :: variant vs std :: any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!