Re: Multiple operator overloading
On Nov 7, 4:21 pm, Andrea Crotti <andrea.crott...@gmail.com> wrote:
James Kanze <james.ka...@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);
}
// ...
};
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?
Like any other operator[]. Except that an additional user
defined conversion is involved (which can affect overload
resolution), it works like any other operator[].
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);
If you also want to use it for assignment, you have to add
assignment operators to the proxy, e.g.:
class Attribute
{
// ...
class Proxy
{
// ...
Proxy const& operator=(int newValue) const
{
owner->setInt(newValue);
return *this;
}
Proxy const& operator=(std::string const& newValue) const
{
owner->setString(newValue);
return *this;
}
...
(Note the use of an operator= which is const. That's a hallmark
of a proxy.)
--
James Kanze