Re: Multiple operator overloading
James Kanze <james.kanze@gmail.com> writes:
On Nov 7, 1:18 pm, Andrea Crotti <andrea.crott...@gmail.com> wrote:
Saeed Amrollahi <amrollahi.sa...@gmail.com> writes:
You can't overload two functions that are different just in return
type. It is
a general concept in "Function-name overloading":
void f(int);
int f(int); // error: only they are different in return types
Same applies to overloaded operators.
Ah true now I got it...
It would have been too easy of course, other ways to get the same target?
The classical solution is to have the function or operator
return a proxy with overloaded conversion operators, e.g.:
class Toto
{
public:
class Proxy
{
Toto const* myOwner;
int myIndex;
public:
Proxy(Toto const* owner, int index)
: myOwner(owner)
, myIndex(index)
{
}
operator int() const { myOwner-
getInt(myIndex); }
operator std::string() const { myOwner-
getString(myIndex); }
};
Proxy operator[](int index) const
{
return Proxy(this, index);
}
// ...
};
--
James Kanze
Last thing, now I rewrote it for my situation:
class Attribute
{
public:
class Proxy
{
Attribute const *owner;
string value;
public:
Proxy(Attribute const* _owner, string& _value)
: owner(_owner), value(_value) {}
operator int() const {
owner->getInt(value);
}
operator std::string() const {
owner->getString(value);
}
};
Proxy operator[](string& index) const {
return Proxy(this, index);
}
int getInt(const string& value) const {
return atoi(value.c_str());
}
string getString(const string& value) const { return value; }
};
But how do I use it?
Where am I supposed to give in the values I want
I thought something like this below but it's not correct, I have to call
the overloaded int which is in the class Proxy, not Attribute.
Attribute x;
x["new"] = int(10);