Get calling this, if exists

Smoke Adams via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 24 10:19:05 PDT 2016


On Friday, 24 June 2016 at 15:35:57 UTC, Steven Schveighoffer 
wrote:
> On 6/24/16 11:15 AM, Smoke Adams wrote:
>> On Friday, 24 June 2016 at 03:16:58 UTC, Meta wrote:
>>> On Friday, 24 June 2016 at 03:10:51 UTC, Mike Parker wrote:
>>>> Oh, perhaps I misunderstood your question. Do you meant this:
>>>>
>>>> class Foo() {
>>>>    void bar() { Log(); }  // Pass reference to Foo instance
>>>> }
>>>>
>>>> void doSomething() { Log(); } // Null reference
>>>>
>>>> If so, the answer is no. And I don't see how that could work 
>>>> as a
>>>> compile time parameter, given that the reference itself is a 
>>>> runtime
>>>> value.
>>>
>>> It actually is possible. You just have to be explicit.
>>>
>>> void log(alias self)(string s)
>>> {
>>>     pragma(msg, self.stringof);
>>> }
>>>
>>> struct Test
>>> {
>>>     void test(string s)
>>>     {
>>>         log!this(s);
>>>     }
>>> }
>>>
>>> void main()
>>> {
>>>     Test t;
>>>     t.test("asdf");
>>> }
>>
>> I don't want to be explicit! One can be explicit with __FILE__ 
>> too but
>> one doesn't have to be.
>
> __FILE__ is a constant, so is __LINE__. __THIS__ would not be, 
> so this is somewhat different.
>
> With UFCS, you can get close:
>
> void log(T)(T obj, string s)
> {
>    ...
> }
>
> struct Test
> {
>    void test(string s)
>    {
>       this.log(s);
>    }
> }
>
> But I believe you have to call with explict 'this'.
>
> Perhaps an opDispatch can help, but seems an awful lot to avoid 
> explicit passing of this variable.
>
> -Steve

The problem with UFCS is that I am using variadic parameters. The 
logging function isn't designed to accept the first parameter as 
this.

It would be much easier to simply have the compiler "insert" it 
using __THIS__. Just because it isn't constant isn't really that 
big of a deal to the compiler. It could just manually add the 
parameter at the end of of the arguments.


I would also have to convert all the calls to this.log.

This becomes problematic because not not all calls are inside 
objects.

We have __FUNCTION__ so, __THIS__ seems somewhat natural. Null 
for outside of objects is fine.




More information about the Digitalmars-d-learn mailing list