Scope variables.

Ali Çehreli acehreli at yahoo.com
Mon Oct 7 15:57:17 PDT 2013


On 10/07/2013 03:52 PM, Agustin wrote:
> On Monday, 7 October 2013 at 19:59:09 UTC, Agustin wrote:
>> On Monday, 7 October 2013 at 19:58:21 UTC, Agustin wrote:
>>> I'm having a hard time trying to use "scoped".
>>>
>>> public T callEvent(T, A...)(auto ref A args) const
>>> {
>>>  T pEvent = scoped!T(forward!args);
>>>  postEvent(pEvent, typeid(T).toHash);
>>>  return pEvent;
>>> }
>>>
>>> private void postEvent(ref Event event, Event.ID type) const
>>> {
>>>  ....
>>> }
>>>
>>> src\event\EventManager.d(37): Error: function
>>> ghrum.event.EventManager.EventManager.postEvent (ref Event event,
>>> uint type) const is not callable using argument types (MyEvent,uint)
>>> src\event\EventManager.d(37): Error: function
>>> ghrum.event.EventManager.EventManager.postEvent (ref Event event,
>>> uint type) const is not callable using argument types (MyEvent,uint)
>>> const
>>> src\event\EventManager.d(37): Error: cast(Event)pEvent is not an lvalue
>>
>>
>> callEvent!MyEvent(); Being MyEvent a subclass of Event.
>
> So i found out that i cannot do this, may i ask why?
>
> public class A
> {
>    int x = 0;
> }
>
> public class B : A
> {
> }
>
> void func(ref A a)
> {
> }
>
> void main()
> {
>    B b = new B();
>    func(b);
> }

Since classes are already references, you would normally pass A, not 
'ref A'.

If you really want to pass 'ref A', perhaps you want to change the 
actual object that an A is referring to:

public class C : A
{}

void func(ref A a)
{
     a = new C;    // <-- A reason for taking 'ref A'
}

However, that would upset the caller, which thinks it has a reference to 
a B object:

void main()
{
   B b = new B();
   func(b);        // <-- Oops! Not a B anymore?
}

Ali



More information about the Digitalmars-d-learn mailing list