Conversation operator as a lval?

M

Matt

Does C++ provide a means to use a conversion operator as a lval?

ie, I want:

class superInt
{
public:
operator int() { return this->value; }
private:
int value;
};

....to instead be this:

class superInt
{
public:
int& operator int() { return this->value; }
private:
int value;
};

....which will not compile.

I suspect the C++ language designers avoided this on purpose, but I
thought I would ask here just in case there is a means to do this (in
some other way then I present above).

Such a thing would save me time re-writing a bunch of overloaded
operators for superInt (among other things).

-Matt
 
V

Victor Bazarov

Matt said:
Does C++ provide a means to use a conversion operator as a lval?\
Sure.

ie, I want:

class superInt
{
public:
operator int() { return this->value; }

Should probably be

operator int() const { return this->value; }
private:
int value;
};

...to instead be this:

class superInt
{
public:
int& operator int() { return this->value; }

operator int&() { return this->value; }
private:
int value;
};

...which will not compile.

Of course.
I suspect the C++ language designers avoided this on purpose,

No, they didn't.
but I
thought I would ask here just in case there is a means to do this (in
some other way then I present above).

Very good choice.
Such a thing would save me time re-writing a bunch of overloaded
operators for superInt (among other things).

But it is rather dangerous. Be careful.

Victor
 
M

Matt

operator int&() { return this->value; }

Great, I'm glad I asked here. Thanks!
But it is rather dangerous. Be careful.

Yes, I can see where it can be quite dangerous. I think I will avoid
it whenever I can...especially since I've already written all my
overloaded operators for the task at hand.

-Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top