来自另一个类的模板运算符专用化
Template operator specialization from another class
所以我正在尝试更改operator+
方法的行为,因为我需要在另一个类的方法中实现较少的方法。如果这里有人能帮我做以下一项或多项工作,我将非常有义务:
- 也许我一直搜索错了?如果是这样,指向正确答案或信息来源的链接会很棒。
- 编写这样的东西的一般方法?
该方案的一些代码示例:
class Rational
{
public:
const Rational Rational::operator+(const Rational &other) const {
Rational ans;
ans._denominator = other.getDenominator() * getDenominator();
ans._numerator = getNumerator() * other.getDenominator() +
other.getNumerator() * getDenominator();
ans.init_rational(); /* <-- This part formats the rational number
every time so that it'd look like 1/2
instead of 2/4(f.e). The purpose of the
specialized method in the other class is
to perform the trace() method where lots
of x+x+x is performed, therefore it'd be
slow and unnecessary to use
"init_rational()" before it's done adding
*/
return ans;
}
};
需要专用运算符 + 的类:
template <class T>
class Matrix
{
private:
int rows, cols;
vector<vector<T>> mat;
public:
const bool trace(T& ans) const
{
if (_rows() != _cols())
{
ans = T();
return false;
}
ans = T();
for (int i = 0; i < _rows(); i++)
{
ans = ans + mat[i][i];
}
return true;
}
}
顺便说一句,我想我想要完成的事情可以在没有我要求的专业化的情况下完成,而是针对整个Rational
类型的专业化,这是这里的实际答案吗?或者我也在寻找一个选项?
PS:如果您觉得需要更多信息/方法,请询问:p
编辑:从我在这里得到的回应来看,我想我不应该按照我想要的方式去做,不过做这样的事情呢?
template <Rational>
const bool trace(Rational& ans) const{
if (_rows() != _cols()){
ans = Rational();
return false;
}
ans = Rational();
for (int i = 0; i < _rows(); i++){
//adding method implemented here or in a separate function in the Rational class
}
return true;
}
你在问题的第一部分提出的要求确实不像巴里所说的那样有意义,考虑到你编辑的信息和评论,这也许是你想要的吗?
bool trace(Rational& ans) const{return true;}
然后
template<typename T>
bool trace(T& ans) const{return false;}
如果是这样,那么您已经非常接近了,只是您需要将模板声明放在顶部并作为泛型类型,而不是相反,您倾向于特定类型:)
不,在Matrix<Rational>
上下文中调用时operator+(Rational, Rational)
不能使它与从其他源调用时执行不同的操作。这没有多大意义,并且严重违反了任何封装概念。
如果您希望在 Matrix
中具有特殊逻辑
ans = ans + mat[i][i];
然后,您可以提供另一层间接寻址,以便内部Matrix
可以针对Rational
所需的内容执行正确的操作:
increment(ans, mat[i][i]);
哪里:
template <typename T>
class Matrix {
private: // <--
template <typename U>
void increment(U& lhs, const U& rhs) {
lhs += rhs;
}
void increment(Rational& lhs, const Rational& rhs) {
// do something else
}
};
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 调用专用模板时出错"no matching function for call to [...]"
- 仅为某些模板专用化定义转换运算符:预期类型/预期类型说明符
- 专用运算符<<模板类的模板类的另一个类
- 使用 = 的模板运算符专用化
- 运算符<<重载时无法访问专用成员(指定指针)
- 来自另一个类的模板运算符专用化
- 运算符重载和模板专用化
- 重载运算符'<<'(左移)的显式专用化
- 如果给定模板不是运算符参数类型的专用模板,则禁用运算符重载
- 为什么 std::atomic<integral> 专用化不提供乘法和除法赋值运算符?
- 类具有运算符()时的结构专用化
- 无法专用化函数模板。重载运算符<<
- 无法访问QXmlStreamReader的专用成员(运算符=)
- C++模板专用化:更改运算符()的返回类型