Hacker News new | ask | show | jobs
by 1718627440 301 days ago
Note that you only need to cast for an upcast. To access the first member, you wouldn't need to cast.

It would be nice though, if syntax like the following would be supported:

    struct A 
    {
        int a;
    };

    struct B 
    {
        int b; 
        struct A a;
    };

    void foo (struct A * a)
    {
        struct B * b;

        &b->a = pa;
    }

    struct B b;

    foo (&b.a);
2 comments

In what scenario would this be useful? If foo() takes a struct A, it should be more generic and have no knowledge about the more specialized struct B.
In exact that same scenario, that you would cast to a subclass in another language, it's about language support for what for example the kernel does with container_of.

Of course casting to a subclass isn't guaranteed to succeed always, but for example when you have actually declared it as the subclass elsewhere it's fine without checking for isinstance.

Yeah you're right, I meant the other way around. Also another loosely related idea is the container_of macro in Linux kernel.
Yeah, my idea is literally native type-safe support of container_of for assignment in the compiler.