C ++ std :: variant vs std :: any [英] C++ std::variant vs std::any

查看:76
本文介绍了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 variants (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆