我有一个带有两个名为Select的函数的类,并返回T和T&的类型。我需要用T&调用函数,但它总是用返回类型T调用函数。 我该如何强制它以T&作为返回类型来调用函数。
这里有两个功能
template <class T>
T Array2D<T>::Select(const int& row, const int& column) const
{
if ((row*this->columns_) + column < 0 || (row*this->columns_) + column >= this->storage_.Length())
{
AdtException exception("Index Out of Bound");
throw exception;
}
return this->storage_[(row*this->columns_) + column];
}
template <class T>
T& Array2D<T>::Select(const int& row, const int& column)
{
if ((row*this->columns_) + column < 0 || (row*this->columns_) + column >= this->storage_.Length())
{
AdtException exception("Index Out of Bound");
throw exception;
}
return (this->storage_[(row*this->columns_) + column]);
}
Here is calling code.
template <class T>
T& Row<T>::operator[](const int& column)
{
T t = this->arr_.Select(row_, column);
T& t1 = t;
return t1;
}
template <class T>
T Row<T>::operator[](const int& column) const
{
return this->arr_.Select(row_, column);
}
这是界面
class IRow
{
public:
virtual ~IRow() = default;
virtual T& operator[](const int& column) = 0;
virtual T operator[](const int& column) const = 0;
};
class IArray2D
{
public:
virtual ~IArray2D() = default;
virtual T Select(const int& row, const int& column) const noexcept(false) = 0;
virtual T& Select(const int& row, const int& column) noexcept(false) = 0;
virtual Row<T> operator[](const int& row) const noexcept(false) = 0;
virtual Row<T> operator[](const int& row) noexcept(false) = 0;
virtual explicit operator bool() const noexcept = 0;
virtual size_t Rows() const noexcept = 0;
virtual size_t Columns() const noexcept = 0;
virtual void Rows(const size_t& rows) noexcept(false) = 0;
virtual void Columns(const size_t& columns) noexcept(false) = 0;
};
答案 0 :(得分:1)
通常不能基于返回类型重载方法,因为调用者无法指定他想要的重载。但是,在您的情况下,方法使用限定符进行了重载:一个const
却没有。这意味着要调用const
版本,您需要在const
对象上调用方法,而非const
版本则相反。例如:
// this will call the T Select(...) const because the array is const
static_cast<const Array2D<T> &>(_arr).Select(_row, column);