c++ - 使用类方法的模板

标签 c++ templates

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

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/

相关文章:

c++ - error : expected constructor, destructor,或者 ‘;’ token CEGUI之前的类型转换

c++ - LLVM Clang 在 OS X 上产生极慢的输入/输出

c++ - 如何在模板类声明体之外实现成员函数?

c++ - operator<< 不能使用其 friend 数组的 IT 成员

c++ - 选择模板参数包中的每个偶数(或奇数)参数

c++ - 匹配模板别名作为模板模板参数

c++ - `BOOST_ENDIAN_BIG_BYTE` 和 `BOOST_ENDIAN_BIG_WORD` 有什么区别?

c++ - BFD_RELOC_64 : Compiling assembler directives on a 32 bit linux with C++

使用 sizeof、malloc 和 cast 的 C++ 对象实例化

c++ - 让函数指针模板参数接受右值引用是否合法?