如果你需要这样的东西,你会怎么做?
假设一个函数 foo 接受一个 void*。
void foo(void* param);
在 foo 的函数定义中,根据条件,它将被类型转换为类 ABC 指针或类 DEF 指针。像这样的东西:
void foo(void* param) {
if (condition) {
ABC* abc = (ABC*) param;
} else {
DEF* abc = (DEF*) param;
}
// Irrespective of abc type, need to use abc quite a bit here. Such as abc->func1() etc.
// So, abc should be made local to foo instead of the condition to use it later.
}
你一般如何解决这个问题?模板可能是一种方式。