如下代码,log 函数接受 Base 类及其子类 Str 、Num 。调用时无需手动指定类型,传入 char* 可自动生成 Str 类,传入 int 可自动生成 Num 类。
struct Base {
void print() {
}
};
struct Str : Base {
Str(const char* s) {}
};
struct Num : Base {
Num(int v) {}
};
template<typename T>
void log(T obj) {
obj.print();
}
int main() {
log("hello");
log(123);
}
如何让模板根据传入的类型推算出用什么类?例如传入 char* 时选择 Str 类,传入 int 时选择 Num 类。