digitalmars.D.learn - Functor alias this
- DaggetJones (32/32) Jun 05 2018 Hi, I'm wondering how I should approach supplying
- Simen =?UTF-8?B?S2rDpnLDpXM=?= (13/45) Jun 05 2018 You'll need to provide a function that returns func. The way it's
Hi, I'm wondering how I should approach supplying functions/delegates around in D. I have option of using classes where the function exists inside the class and to provide different functionality different classes are created. Alternatively I could just pass the function directly around without all the weight of the class. This led me to wonder if there is a way to combine the two methods? With D's alias this would it be possible to have the user code treat the function as a delegate but define the functions actually in a class without any restrictions? import std.stdio; alias MyFunction = int delegate(); class MyFunctor { alias func this; int MyData = 5; int func() { return MyData; } } void bar(MyFunction foo) { writeln(foo()); } void main() { MyFunctor f = new MyFunctor(); bar(&f.func); // but not // bar(f); or bar(&f); } But I would like to simply pass the class as if it were the member func, which is what the alias this is suppose to provide. It seems D ignores the alias this in this case?
Jun 05 2018
On Wednesday, 6 June 2018 at 06:25:49 UTC, DaggetJones wrote:Hi, I'm wondering how I should approach supplying functions/delegates around in D. I have option of using classes where the function exists inside the class and to provide different functionality different classes are created. Alternatively I could just pass the function directly around without all the weight of the class. This led me to wonder if there is a way to combine the two methods? With D's alias this would it be possible to have the user code treat the function as a delegate but define the functions actually in a class without any restrictions? import std.stdio; alias MyFunction = int delegate(); class MyFunctor { alias func this; int MyData = 5; int func() { return MyData; } } void bar(MyFunction foo) { writeln(foo()); } void main() { MyFunctor f = new MyFunctor(); bar(&f.func); // but not // bar(f); or bar(&f); } But I would like to simply pass the class as if it were the member func, which is what the alias this is suppose to provide. It seems D ignores the alias this in this case?You'll need to provide a function that returns func. The way it's currently written, the alias this would basically translate to bar(f.func()): class MyFunctor { alias func2 this; int MyData = 5; int func() { return MyData; } auto func2() { return &func; } } -- Simen
Jun 05 2018