我正在尝试使用运算符重载为数组切片分配一些很好的语法。由于引用的const正确性的一些特性,左值和右值切片需要不同的类。但是,我无法让编译器了解在给定的上下文中使用哪个版本。
下面的代码显示了原始代码的简化版本,虽然看起来有点做作,但它可以很好地捕获问题。在实际代码中,i
是一整套索引,而B
/ ConstB
表示无法复制的大型数组的片段,从而激励引用x
。 / p>
当我想在foo
中进行分配时,会出现问题。我希望右边的所有切片都产生一个ConstB
对象,但由于a1
在这种情况下恰好是非const,所以使用了错误的对象。我可以通过引入const_cast
来强制执行它,但我更喜欢某种不破坏用户代码的方式(即foo
内的东西)。有没有办法强制分别为左值或右值调用给定的重载?
代码:
struct B;
struct ConstB;
struct A
{
double data[10];
A() {}
A& operator=(const ConstB &b);
ConstB operator()(int i) const;
B operator()(int i);
};
struct B
{
double &x;
B(double *d, int i);
B& operator=(const A &a);
};
struct ConstB
{
const double x;
ConstB(const double *d, int i);
};
A& A::operator=(const ConstB &b) {
data[0] = b.x;
return *this;
}
ConstB A::operator()(int i) const {
return ConstB(data,i);
}
B A::operator()(int i) {
return B(data,i);
}
B::B(double *d, int i)
: x(d[i]) {}
B& B::operator=(const A &a) {
x=a.data[0];
return *this;
}
ConstB::ConstB(const double *d, int i)
: x(d[i]) {}
void foo(A &a1, A &a2, A&a3)
{
a1(2) = a2;
a3 = a1(3);
// a3 = const_cast<const A&>(a1)(3);
}
int main(int argc, char *argv[])
{
A a1;
A a2;
A a3;
foo(a1,a2,a3);
return 0;
}
产生的错误消息:
test.cc: In function ‘void foo(A&, A&, A&)’:
test.cc:67:6: error: no match for ‘operator=’ (operand types are ‘A’ and ‘B’)
a3 = a1(3);
^
test.cc:36:4: note: candidate: A& A::operator=(const ConstB&)
A& A::operator=(const ConstB &b) {
^
test.cc:36:4: note: no known conversion for argument 1 from ‘B’ to ‘const ConstB&’
test.cc:5:8: note: candidate: A& A::operator=(const A&)
struct A
^
test.cc:5:8: note: no known conversion for argument 1 from ‘B’ to ‘const A&’
test.cc:5:8: note: candidate: A& A::operator=(A&&)
test.cc:5:8: note: no known conversion for argument 1 from ‘B’ to ‘A&&’