View mode: basic / threaded / horizontal-split · Log in · Help
October 16, 2012
Returning reference to integer from property setter function
Hi! How I can return from function a reference to int? Here is a
simple code, to demonstrate my problem:

struct Foo {
public:
	@property int foo() const
	{
		return x_;
	}
	
	@property ref int foo(int value)
	{
		x_ = value;
		return x_;
	}
	
private:
	int x_;
}


void main()
{
	auto f = Foo;
	f.foo += 5;
}


When I try to build this code, I get the error at line "f.foo +=
5" with message: "Error: f.foo() is not an lvalue". I thought the
ref qualifier causes the compiler to return a reference in that
case.
October 16, 2012
Re: Returning reference to integer from property setter function
On Tuesday, 16 October 2012 at 14:43:09 UTC, m0rph wrote:
> Hi! How I can return from function a reference to int?

The problem here isn't about the ref but rather the way 
properties are implemented with +=. I believe this is one of the 
older still-standing D bugs.

It rewrites your expresssion to be

f.foo() += 5;

and the problem is the foo getter returns a plain int which isn't 
an lvalue.


If your getter returned a ref, it would work, but it wouldn't 
call the setter.

The setter is (right now, and probably for a while to come) only 
called on plain assignment.

f.foo = f.foo + 5;

That should work with your current code, being rewritten as 
f.foo(f.foo() + 5), but += won't.



But anyway if you just use the getter and have it return a ref, 
you can use += but then you lose the setter function.
October 16, 2012
Re: Returning reference to integer from property setter function
Thanks for reply, hopefully this issue will be fixed sometime..
Top | Discussion index | About this forum | D home