恢复任何类型 [英] Restoring any type
问题描述
有什么方法来恢复类型的打包到boost ::任何对象?如果现在,我可以存储一些关联映射吗?我需要类似(伪代码):
are there any ways to restore type of packed into boost::any object? If now, can I store some association map for it? I need something like (pseudocode):
map<key, any> someMap;
someMap["Key"] = some own object;
getType("Key");
推荐答案
不是任意的,你需要一些静态类型
Not arbitrarily, you need to have some static type(s) you want to work with in C++.
因此,你可以使用 any :: type()测试或转换为特定的类型。 / code>和
any_cast()
,例如:
So you can test for or cast to a specific type using any::type()
and any_cast()
, e.g.:
const boost::any& any = someMap["Key"].type();
if (int* i = boost::any_cast<int>(&any)) {
std::cout << *i << std::endl;
} else if (double* d = boost::any_cast<double>(&any)) {
// ...
但是,由于C ++是静态类型的,所以不能像下面这样:
But something like the following can not be done in general due to C++ being statically typed:
magically_restore_type(someMap["Key"]).someMethod();
使用 boost :: any
C ++几乎总是不是一个好主意,完全是因为处理任意类型是没有乐趣。如果你只需要处理一个已知的有限集合类型,不要使用 boost :: any
- 有更好的选择,例如 boost :: variant
或多态类。
Using something like boost::any
in C++ is almost always not a good idea, exactly because handling arbitrary types is no fun. If you only need to handle a known finite set of types, don't use boost::any
- there are better options like boost::variant
or polymorphic classes.
这篇关于恢复任何类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!