我有模板方法,我希望模板方法使用类中的特定方法来执行操作。可能吗?
template<typename T>
int minus(T t1,T t2){
return t1-t2;
}
在我的苹果对象类中,我有一个名为 getPrice() 的方法 我怎样才能将两者结合起来。
这是正确的吗?
template<typename T>
int minus(T t1,T t2){
return t1.getPrice()-t2.getPrice();
}
最佳答案
为此,您可能需要一个普通函数用于您的类型:
template <class T>
int minus(T t1, T t2) {
return t1 - t2;
}
int minus(const apple& t1, const apple& t2) {
return t1.getPrice() - t2.getPrice();
}
关于c++ - 使用类方法的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331638/