[英]boost::any_cast - throw only when an implicit conversion isn't available?
I want boost::any_cast<T>
to only throw an exception when the type of the any
doesn't have an implicit conversion to T
. 我希望
boost::any_cast<T>
只在any
的类型没有隐式转换为T
时抛出异常。 The normal behaviour seems to be to throw an exception if the type of the any
is not T
, regardless of implicit conversions. 如果
any
的类型不是T
,则正常行为似乎是抛出异常,而不管隐式转换。
Example: 例:
boost::any a = 1;
boost::any_cast<int>(a); // This succeeds, and rightfully so
boost::any_cast<long>(a); // I don't want this to throw
boost::any_cast<Widget>(a); // I want this to throw
Could anyone tell me if there's a simple way to get the functionality I want, or better yet give me a good reason for why the existing behaviour is the way it is? 任何人都可以告诉我是否有一种简单的方法来获得我想要的功能,或者更好地为我提供一个很好的理由来解释现有行为的原因是什么?
Well you can't do it. 那么你不能这样做。 The
any
mechanism works like this: any
机制都是这样的:
struct base {
virtual ~base() { }
};
template<typename T>
struct concrete_base : base {
T t;
concrete_base(T t):t(t) { }
};
struct my_any {
base * b;
template<typename T>
my_any(T t):b(new concrete_base<T>(t)) { }
template<typename T>
T any_cast() {
concrete_base<T> * t = dynamic_cast< concrete_base<T>* >(b);
if(!t) throw bad_any_cast();
return t->t;
}
};
I hope it's clear what the above does. 我希望上面的内容清楚。 There is no way you could do what you are looking for i think.
我认为你无法做你正在寻找的事情。 The reason is that there is no information about the type kept that could prove useful here.
原因是没有关于保留的类型的信息在这里可能有用。 RTTI doesn't provide it.
RTTI不提供它。
any_cast不能这样做但是如果基类和派生类型是完整的(它们通常用于层次结构中的类型)你可以实现自己的系统,它通过throw和catch转换,因为抛出指向派生的指针type可以作为基类指针类型捕获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.