使用类方法的模板

M.A*_*M.A 0 c++ templates

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

template<typename T>
int minus(T t1,T t2){
return t1-t2;
}
Run Code Online (Sandbox Code Playgroud)

在我的apple对象类中,我有一个名为getPrice()的方法如何将两者结合起来.

它是否正确 ?

template<typename T>
int minus(T t1,T t2){
return t1.getPrice()-t2.getPrice();
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ker 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();
}
Run Code Online (Sandbox Code Playgroud)