【发布时间】:2016-12-01 13:12:59
【问题描述】:
我有一个模板类 foo(本质上是一个矩阵)。 foo 的模板参数只能是int、float 或double,即不能是const int。这样做的原因是我有专门的运算符来处理这些,而为 const 情况复制运算符似乎是多余的。我有两个get_data 函数,它们返回一个具有适当常量的指针。但我也不想选择单行并返回const foo 的row 函数,这样调用者就无法修改返回的对象。
我的问题:
1) 我怎样才能使 B 成为常量?
2) 我应该为例如创建运算符函数吗?富?
2) 我应该创建一个reference_foo 类吗?
template <class T>
class foo
{
using uint8_t = unsigned char;
int rows = 0;
int cols = 0;
T * data = nullptr;
bool reference = false;
public:
foo() = default;
//foo(const foo&) // this is not included here for simplicity
//foo& operator=(const foo&) // this is not included here for simplicity
foo(int r, int c) : rows(r), cols(c)
{
data = new T[rows * cols];
}
~foo()
{
if (!reference)
{
delete[] data;
}
}
T * get_data()
{
return data;
}
T const * get_data() const
{
return data;
}
const foo row(int r) const
{
foo t;
t.rows = 1;
t.cols = cols;
t.reference = true;
// t.data = get_data() + r * cols; // ERROR: invalid conversion from 'const uint8_t*' to 'uint8_t*'
t.data = const_cast<T*>(get_data()) + r * cols; // Not pretty, but "ok" if the returned object is const
return t;
}
};
int main()
{
const foo<int> A(2, 1);
// A.get_data()[0] = 1; // ERROR: assignment of read-only location, perfectly catched by compiler
auto B = A.row(1);
B.get_data()[0] = 1; // B is not const... overwritten...
return 0;
}
为简单起见,省略了运算符函数。
【问题讨论】:
-
我得到这个然后错误(如果我使用
const int作为模板参数并尝试使用运算符):'operator+='不匹配(操作数类型是'foo'和' foo ') -
sry 链接错误,我会寻找更好的
-
我认为选项 #3
const_foo是最干净的选项。 -
@SamVarshavchik 我喜欢它,从语法的角度来看(它类似于
const_iterator),但是我必须制作大量的函数来处理这两个类在一起。 -
不一定,如果你让
foo继承自const_foo,并实现const_foo中的所有const方法,使用protected指针,以及存储在@987654337中的标志@ 和using来自foo的所有 const 方法。对于大多数 C++ 库容器,iterator继承自const_iterator。