Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过实现两个常量不同的函数来避免代码重复_C++ - Fatal编程技术网

C++ 通过实现两个常量不同的函数来避免代码重复

C++ 通过实现两个常量不同的函数来避免代码重复,c++,C++,我有一个通用的矩阵类,还有两个版本的操作符(), 返回索引的常量引用的常量方法, 还有一个非常量方法,它返回对索引的非常量引用(这允许我更改它) 我试图通过使用const_cast并调用const版本来使用非const版本,但由于某些原因,它不起作用: template<typename T> class Matrix { std::vector<T> _matrix; unsigned int _rows; unsigned int _cols

我有一个通用的
矩阵
类,还有两个版本的
操作符(),
返回索引的常量引用的常量方法,
还有一个非常量方法,它返回对索引的非常量引用(这允许我更改它)

我试图通过使用const_cast并调用const版本来使用非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));
    }
};
模板
类矩阵
{
std::向量_矩阵;
无符号整数行;
无符号整数;
公众:
常量T&运算符()(无符号整数行,无符号整数列)常量
{
返回_矩阵[col+(_cols*row)];
}
运算符()(无符号整数行,无符号整数列(&O)
{
返回常量转换(静态转换(*this).operator(行,列));
}
};
它不允许我将(行、列)添加到最后一行的运算符中。有什么想法吗?

您就快到了:

return const_cast<T&>(const_cast<const Matrix*>(this)->operator()(row, col));
return const_cast(const_cast(this)->operator()(row,col));

在这里,代码重复是两个坏处中较小的一个。只需在非
常量版本中重复表达式
\u matrix[col+(\u cols*row)]
。不要与语言对抗


要调用
const
版本,您需要
const\u cast
this
指针。您使用的表达式是
const\u cast(const\u cast(this)->operator()(行,列))
这是一个相当难阅读的代码,并且包含了两次令人不安的
常量。

我的拙见是,这不是一个你想要避免代码重复的情况。因此我建议如下:

const T& operator()(unsigned int row, unsigned int col) const {
  return _matrix[col + (_cols * row)];
}

T& operator()(unsigned int row, unsigned int col) {
  return _matrix[col + (_cols * row)];
}

它的可读性也比使用
const_cast
的版本更高,并且可能更快,因为您可以避免不必要的堆栈帧。

投票:您在我之前2分钟就找到了表达式。Make macro可能重复。您仍然可以获得代码重复,但可以隐藏50%的代码。您可以通过添加两倍于太多的代码,让它变得更复杂。对我来说似乎不是一场胜利。