C++ Logo

std-proposals

Advanced search

std::any / std::any_cast without typeid

From: Nikolay Mihaylov <nmmm_at_[hidden]>
Date: Sat, 5 Dec 2020 21:30:15 +0200
Consider following code:

    struct A{
      virtual ~A() = default;
      virtual int op(int a, int b) const = 0;
    };

    struct Sum : A{
        int op(int a, int b) const override{
            return a + b;
        }
    };

    #include <any>

    std::any x = Sum{};

    int main(){
        return std::any_cast<A &>(x).op(5, 5);
    }

It crashes with `std::bad_any_cast` exception.

this happens, because *std::any_cast* is specified in terms of *typeid*.

I also know how to fix this.

However I can not understand why this *should* happen. Reference is pointer
under the hood, so cast should work, e.g. following works OK.

Maybe we need some other kind of cast, for example
*std::non_secure_any_cast* that just casts the value no matter what.

We can not really call it "dynami_any_cast", because it will work the same
way for *int* -> *long* or *unsigned* -> *float*.

Of course the price if we made the wrong cast the program will crash, but I
can make the program crash with the current *std::any_cast* implementation
as well.

Current *std::any_cast* does not behave the way programmers expect:

Consider this code:

    int main(){
        Sum s;
        A &a = s;

        return a.op(5, 5);
    }

and this code too:

    int main(){
        Sum s;
        A *a = &s;

        return a->op(5, 5);
    }

Received on 2020-12-05 13:30:54