c++ - 通过实现两个 const 不同的函数来避免代码重复

标签 c++

我有一个通用的 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/

相关文章:

c++ - OpenGL ES 2.0 2D 投影矩阵,将 GLfloat (*)[4] 转换为 GLfloat 时出错

c++ - 在c++中实现hashmap的过程中发生了奇怪的事情

c++ - 在 (Neo)vim 中调试 C++

c++ - 开发iOS应用最常见的方法是什么?

c++ - C++ 中的多层命名空间规范

c++ - 指向空指针

c++ - 在 Qt 项目、Visual Studio 中添加按钮单击处理程序

c++ - 别名成员对象方法的最佳方法? "Passthrough methods"

c++ - 微软对lstrcmpi和Unicode字符的实现

c++ - 使用 malloc() 时如何实现复制构造函数