reinterpret_cast vector of class A to vector of class B

前端 未结 3 586
抹茶落季
抹茶落季 2020-12-22 08:21

Say I have two classes A and B, and a vector of class A as below:

class A {
    int foo;
    int bar;
    void someMet         


        
相关标签:
3条回答
  • 2020-12-22 08:47

    You might be able to get away with making a union type C which can be read as int or uint and making a vector of that instead.

    union C {
        int s;
        uint u;
    };
    
    std::vector<C> va;
    

    But that won't work if you need to pass it into a method that expects a vector<uint>.

    In my opinion the right way to fix this is to make the method that expects a vector into a template so that it can accept any container type. Even better, make it like the STL methods and take an iterator or iterator pair.

    0 讨论(0)
  • 2020-12-22 08:53

    The program behaviour is undefined since the types are unrelated.

    One solution is to write a cast operator to copy a class B instance to a class A instance. In class B, write

    operator A() const
    {
        A a;
        a.foo = this->foo; // ToDo - check `this->foo` is an appropriate size
        a.bar = this->bar; // ToDo - check `this->bar` is an appropriate size
        return a; // compiler will elide the value copy
    }
    
    0 讨论(0)
  • 2020-12-22 09:03

    Don't. Any way you think you can do it results in undefined behaviour. Create a new vector and copy over the values.

    0 讨论(0)
提交回复
热议问题