试图在没有基类和虚拟调用的情况下获得编译时方法和对象选择。
情况如下:
struct A {
void f1()const { cout << "A::f1" << endl;}
void f2()const { cout << "A::f2" << endl;}
};
struct B {
void f1()const { cout << "B::f1" << endl;}
void f2()const { cout << "B::f2" << endl;}
};
class Holder {
A* _a = nullptr;
B* _b = nullptr;
public:
Holder(A* a): _a(a) {}
Holder(B* b): _b(b) {}
void f1()const {
if(_a) _a->f1();
else if(_b) _b->f1();
}
void f2()const {
if(_a) _a->f2();
else if(_b) _b->f2();
}
};
void f(const Holder& h) {
h.f1();
}
int main() {
B obj;
Holder h(&obj);
f(h);
}
http://coliru.stacked-crooked.com/a/4b5acec6866cfd4e
假设像 A 和 B 这样的类很少,但可能有很多像 f1 和 f2 这样的函数。
持有者需要在它持有的实际对象上调用函数,没有多态性,也不需要 A 和 B 的继承/共享接口。
寻找一种好方法来做类似的事情:
class Holder {
A* _a = nullptr;
B* _b = nullptr;
public:
Holder(A* a): _a(a) {}
Holder(B* b): _b(b) {}
// below is pseudo code!
void call<function>()const {
if(_a)
_a->function(); // function is known in compile time, sort of...
else if(_b)
_b->function();
}
void f1()const { call<f1>(); }
void f2()const { call<f2>(); }
};
任何想法?
- 宏?
- 模板?
- 其他技巧?