简体   繁体   中英

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 . The normal behaviour seems to be to throw an exception if the type of the any is not T , regardless of implicit conversions.

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:

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.

any_cast不能这样做但是如果基类和派生类型是完整的(它们通常用于层次结构中的类型)你可以实现自己的系统,它通过throw和catch转换,因为抛出指向派生的指针type可以作为基类指针类型捕获。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM