使用类方法的模板

时间:2012-11-11 13:41:37

标签: c++ templates

我有模板方法,我希望模板方法使用类中的特定方法来执行操作。有可能吗?

template<typename T>
int minus(T t1,T t2){
return t1-t2;
}

在我的apple对象类中,我有一个名为getPrice()的方法 我怎样才能将两者结合起来。

这是对的吗?

template<typename T>
int minus(T t1,T t2){
return t1.getPrice()-t2.getPrice();
}

1 个答案:

答案 0 :(得分:5)

为此你可能想要一个类型的普通函数:

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();
}