reinterpret_cast は参照に対しても使用できる【C++】

reinterpret_cast はポインタの型変換を行うという説明をよく目にします。 しかし、それだけではなく参照のキャストも行えるということをメモしておきます。

コード

#include <iostream>

struct Point {
    int x;
    int y;
};

struct Size {
    int width;
    int height;
    int area(){ return width * height; }
};

int main()
{
    Point p = { 25, 50 };
    Size& s = reinterpret_cast<Size&>(p);
    std::cout << s.area() << "(" << s.width << "x" << s.height << ")" << std::endl;
    
    s.width = 125;
    s.height = 300;
    std::cout << p.x << ", " << p.y << std::endl;
}

上記のコードは Wandbox で動作を確認しました。

wandbox.org

参考

msdn.microsoft.com