我有一个通用的 Matrix
类,我有两个版本的 operator()
,
返回对索引的 const 引用的 const 方法,
和一个非常量方法,该方法返回对索引的非常量引用(这允许我更改它。
我尝试通过使用 const_cast 并调用 const 版本来使用非常量版本,但由于某些原因它不起作用:
template<typename T>
class Matrix
{
std::vector<T> _matrix;
unsigned int _rows;
unsigned int _cols;
public:
const T& operator()(unsigned int row, unsigned int col) const
{
return _matrix[col + (_cols * row)];
}
T& operator()(unsigned int row, unsigned int col)
{
return const_cast<T&>(static_cast<const Matrix*> (*this).operator(row, col));
}
};
它不允许我在最后一行将 (row, col) 添加到运算符。有什么想法吗?
最佳答案
在这里,代码重复是两害相权取其轻。只需重复表达式 _matrix[col + (_cols * row)]
在非 const
版本。不要与语言作斗争。
调用const
版本,你需要 const_cast
this
指针。你所追求的表达是 const_cast<T&>(const_cast<const Matrix*>(this)->operator()(row, col));
阅读起来要困难得多,并且确实包含令人不安的 const_cast
;两次。
关于c++ - 通过实现两个 const 不同的函数来避免代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39832140/