Здравствуйте, kov_serg, Вы писали:
_>Как такое написать по Сиплюсплюсному что бы без 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;
_>}
_>
|
| | |
#include <stdio.h>
struct I1
{
virtual void show()=0;
};
struct I2
{
virtual void print()=0;
};
struct A : I1,I2
{
int x[3];
void show() { printf("show x0=%d\n",x[0]); }
void print() { printf("print x0=%d\n",x[0]); }
I1* i1 = { this };
I2* i2 = { this };
};
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;
}