U
usao
Does anyone have an example of how to create a class which describes
and array, such that I can use the subscript operator[] on both the
left and right side of an assignment statement? This is as close as I
can get, but I feel it's kludgey and slow...
#include <iostream.h>
template<class T>
class foo {
T *data;
public:
foo(int size) { data=new T[size]; }
~foo() { delete[] data; }
class helper {
T &item;
public:
helper(T &item_) : item(item_) {}
T &operator=(const T& other) {
cout <<"nonconst used as lvalue\n";
item=other;
return item;
}
operator const T&() const {
cout <<"nonconst used as rvalue\n";
return item;
}
};
helper operator[](int index) {
//don't know yet whether we are being used as l or r value
return helper(data[index]);
}
const T& operator[](int index) const {
cout <<"const used as rvalue\n";
return data[index];
}
};
int main()
{
foo<int> x(10);
const foo<int> &y=x;
cout <<"--- performing x[3]=10\n";
x[3]=10; //OK: nonconst used as lvalue
//cout <<"y[3]=11\n";
//y[3]=11; //BAD: const used as lvalue
cout <<"--- performing a=x[3]\n";
int a=x[3]; //OK: nonconst used as rvalue
cout <<"--- performing b=y[3]\n";
int b=y[3]; //OK: const used as rvalue
cout <<"--- performing x[3]=x[3]+5\n";
x[3]=x[3]+5; //OK: nonconst used as rvalue, then as lvalue
cout <<"result: x3 is " <<x[3] <<"\n";
return 0;
}
and array, such that I can use the subscript operator[] on both the
left and right side of an assignment statement? This is as close as I
can get, but I feel it's kludgey and slow...
#include <iostream.h>
template<class T>
class foo {
T *data;
public:
foo(int size) { data=new T[size]; }
~foo() { delete[] data; }
class helper {
T &item;
public:
helper(T &item_) : item(item_) {}
T &operator=(const T& other) {
cout <<"nonconst used as lvalue\n";
item=other;
return item;
}
operator const T&() const {
cout <<"nonconst used as rvalue\n";
return item;
}
};
helper operator[](int index) {
//don't know yet whether we are being used as l or r value
return helper(data[index]);
}
const T& operator[](int index) const {
cout <<"const used as rvalue\n";
return data[index];
}
};
int main()
{
foo<int> x(10);
const foo<int> &y=x;
cout <<"--- performing x[3]=10\n";
x[3]=10; //OK: nonconst used as lvalue
//cout <<"y[3]=11\n";
//y[3]=11; //BAD: const used as lvalue
cout <<"--- performing a=x[3]\n";
int a=x[3]; //OK: nonconst used as rvalue
cout <<"--- performing b=y[3]\n";
int b=y[3]; //OK: const used as rvalue
cout <<"--- performing x[3]=x[3]+5\n";
x[3]=x[3]+5; //OK: nonconst used as rvalue, then as lvalue
cout <<"result: x3 is " <<x[3] <<"\n";
return 0;
}