Hacker News new | past | comments | ask | show | jobs | submit login

Two types must be the same size, if they weren't how would sizeof() work, or vector<> for that matter.



This problem is also on stackoverflow: http://stackoverflow.com/a/1391001.

It solved it by wrapping with a superclass that you downcast from. You won't be able to work with them by value due to object slicing but you can still have a vector of pointers:

    vector<Panda_without_bamboo*> pandas;
I am not sure how to do the downcasting though. Assuming the classes look like this:

    public Panda_without_bamboo
    {
       int bambooCount;
    }

    template<std::size_t N>
    class Panda_with_bamboo : public Panda_without_bamboo
    {
       int a;
       int b;
       Bamboo bamboo[N];
    }
You can't really do:

    static_cast<Panda<pandas[0].bambooCount>*>(pandas[0])


So it does seem like using flexible array members (first answer in that stackoverflow and the topic discussed in this submission) is a cleaner solution if you need contiguous allocation: http://www.codeatcpp.com/2007/10/dynamic-array-template.html


Of course you can create a vector of pointers and do whatever you want.

If you need contiguous memory though this is likely a terrible way to go about it since you are not only having to dereference pointers that could go anywhere, but each one will mean a separate heap allocation which will be slow for small objects and not scale with concurrency.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: