我什么时候应该使用std :: any [英] When should I use std::any
问题描述
由于引入了C ++ 17 std::any
.现在可以编写这样的代码
Since C++17 std::any
is introduced. One can now write code like this
#include <iostream>
#include <any>
#include <string>
int main () {
const double d = 1.2;
std::any var = d;
const std::string str = "Hello World";
var = str;
}
为变量var
分配了一个双精度,然后为它分配了std::string
.
A double is assigned to the variable var
and than a std::string
was assigned to it.
为什么要引入std::any
?
我认为这违反了least astonishment rule
,因为我很难想到一种情况,在这种情况下可以用这种方式更清楚地表达我喜欢表达的内容.
I think this is violating the least astonishment rule
, because I find it hard to think of a situation, where this can be used to express more clearly, what I like to express.
在std::any
有益的情况下,有人可以给我一个很好的例子.
Can somebody give me a good example, when std::any
is beneficial.
https://gcc.godbolt.org/z/-kepOD
推荐答案
何时使用
void*
是在某些有限用例中极为不安全的模式,std::any
增加了类型安全性,这就是为什么它具有一些实际用例的原因.
When to Use
void*
as an extremely unsafe pattern with some limited use cases, std::any
adds type-safety, and that’s why it has some real use cases.
一些可能性:
- 在库中-当库类型必须保留或传递任何内容而又不知道
一组可用的类型.
- 解析文件-如果您确实无法指定支持的内容
类型.
- 消息传递.
- 使用脚本语言进行绑定.
- 为脚本语言实现解释器
- 用户界面-控件可能包含任何内容
- 编辑器中的实体
(参考)
- In Libraries - when a library type has to hold or pass anything without knowing the
set of available types.
- Parsing files - if you really cannot specify what are the supported
types.
- Message passing.
- Bindings with a scripting language.
- Implementing an interpreter for a scripting language
- User Interface - controls might hold anything
- Entities in an editor
(ref)
这篇关于我什么时候应该使用std :: any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!