Aliasing struct and array the C++ way

后端 未结 4 1034
北海茫月
北海茫月 2020-12-05 09:45

This is a C++ followup for another question of mine

In the old days of pre-ISO C, the following code would have surprised nobody:

struct Point {
             


        
4条回答
  •  有刺的猬
    2020-12-05 10:21

    Use an constexpr array of pointer-to-member:

    #include 
    
    struct Point {
        double x;
        double y;
        double z;
    };
    
    double dist(struct Point *p1, struct Point *p2) {
        constexpr double Point::* coords[3] = {&Point::x, &Point::y, &Point::z};
    
        double d2 = 0;
        for (int i=0; i<3; i++) {
            double d = p1->*coords[i] - p2->*coords[i];
            d2 += d * d;
        }
        return sqrt(d2);
    }
    

提交回复
热议问题