最近设计中遇到比较挠头的一个问题,就是如何通过类模板成员函数(由于设计需要,难以通过模板类实现)实现多种类型的访问,先给出问题在哪里,用一个简单的例子说明,例子如下:
class Dog {
int age;
std::string name;
public:
void init(std::string dname, int dage) {
name = dname;
age = dage;
}
void print() {
std::cout << "dog " << name << " age " << age << std::endl;
}
};
class Cat {
int age;
std::string name;
public:
void init(std::string dname, int dage) {
name = dname;
age = dage;
}
void print() {
std::cout << "cat " << name << " age " << age << std::endl;
}
};
class PrintCla {
public:
template<typename T>
void print(T* animal) {
ainmal->print();
}
};
int main() {
Dog dog;
dog.init("dd", 12);
Cat cat;
cat.init("cc", 13);
PrintCla printcla;
printcla.print(&cat);
return 0;
}