Как такое написать по Сиплюсплюсному?
От: kov_serg Россия  
Дата: 21.03.25 07:20
Оценка:
Как такое написать по Сиплюсплюсному что бы без UB

#include <stdio.h>

template<class A,class B>A*parent_of(B*self,B A::*t) { 
    return (A*)((char*)self-(char*)(&(((A*)0)->*t)));
}
template<class A,class B>A*parent_of(B*self,B(A::*t)[1]) { 
    return (A*)((char*)self-(char*)(&(((A*)0)->*t)));
}

struct I1 { virtual void show()=0; };
struct I2 { virtual void print()=0; };

struct A {
    int x[3];
    struct :I1 {
        A* parent() { return parent_of(this,&A::i1); }
        void show() { printf("show x0=%d\n",parent()->x[0]); }
    } i1[1];
    struct :I2 {
        A* parent() { return parent_of(this,&A::i2); }
        void print() { printf("print x0=%d\n",parent()->x[0]); }
    } i2[1];
};

void fn(I1* i) { i->show(); }
void fn(I2* i) { i->print(); }

int main(int argc, char **argv) {
    A a[1];
    a->x[0]=123;
    fn(a->i1);
    fn(a->i2);
    return 0;
}
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.