why doesn't std::any_cast support implicit conversion?

后端 未结 5 942
傲寒
傲寒 2020-12-24 12:33

Why does std::any_cast throw a std::bad_any_cast exception when an implicit conversion from the actual stored type to the requested type would be p

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 13:07

    This question is not well posed; implicit conversion to the right type are in principle possible, but disabled. This restriction probably exists to maintain a certain level of safety or to mimic the explict cast necessary (through pointer) in the C-version of any (void*). (The example implementation below shows that it is possible.)

    Having said that, your target code still doesn't work because you need to know the exact type before conversion, but this can in principle work:

    any a = 10;  // holds an int now
    long b = int(a); // possible but today's it should be: long b = any_cast(a);
    

    To show that implicit conversions are technically possible (but can fail at runtime):

    #include
    
    struct myany : boost::any{
        using boost::any::any;
        template operator T() const{return boost::any_cast(*this);}
    };
    
    int main(){
    
        boost::any ba = 10;
    //  int bai = ba; // error, no implicit conversion
    
        myany ma = 10; // literal 10 is an int
        int mai = ma; // implicit conversion is possible, other target types will fail (with an exception)
        assert(mai == 10);
    
        ma = std::string{"hello"};
        std::string mas = ma;
        assert( mas == "hello" );
     }
    

提交回复
热议问题