有没有办法恢复压缩到 boost::any 对象的类型?如果现在,我可以为它存储一些关联图吗?我需要类似(伪代码)的东西:
map<key, any> someMap;
someMap["Key"] = some own object;
getType("Key");
您是要获取值的类型,还是只是将其转换回原来的值?如果您只想投射它,只需使用boost::any_cast
:
boost::any val = someMap["Key"];
RealType* r = boost::any_cast<RealType>(&val);
不是随意的,你需要有一些你想在 C++ 中使用的静态类型。
any::type()
因此,您可以使用and测试或转换为特定类型any_cast()
,例如:
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++ 是静态类型的,因此通常无法执行以下操作:
magically_restore_type(someMap["Key"]).someMethod();
在 C++ 中使用类似的东西boost::any
几乎总是不是一个好主意,正是因为处理任意类型并不有趣。如果您只需要处理已知的有限类型集,请不要使用boost::any
- 有更好的选项,例如boost::variant
或多态类。
假设您确实有这样一个函数来从 boost::any 中提取正确类型的提取。这个函数的返回值是多少?你的代码会是什么样子?
// Extracts v and returns the correct type... except we can't do that in C++. Let's just call it MagicalValue for now.
MagicalValue magic(const boost::any& v);
void perform_magic(const boost::any& v)
{
MagicalValue r = magic(v);
r.hello_world(); // Wait, what?
}
你不能在静态类型语言中做这种类型的诡计。您可以尝试的是多态性而不是 boost::any。这为您提供了一个可以在 C++ 中使用的通用接口。