www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Problem with aliasing member function

reply Andrey <saasecondbox yandex.ru> writes:
Hello,
I can't compile this piece of code:
 struct Object
 {
     void run(wstring ending, uint index)(int number)
     {
 
     }
 }
 
 void tester(alias callback, T)(int number, T object = null)
 {
     static if(is(T == typeof(null))) alias handler = callback;
     else auto handler(wstring ending, uint index) = 
 object.callback!(ending, index);
         	handler!("rfv", 5)(word);
 }
 
 void main()
 {
     Object obj;
     tester!(Object.run)(10, &obj);
 }
Here in tester I want to alias a template method and call it on object if this object isn't null. But I don't understand how to do it. How to solve the problem?
Aug 18 2019
parent rjframe <dlang ryanjframe.com> writes:
On Sun, 18 Aug 2019 19:17:16 +0000, Andrey wrote:

 Here in tester I want to alias a template method and call it on object
 if this object isn't null. But I don't understand how to do it.
 How to solve the problem?
I don't think you can alias an object method directly; three methods I know of: --- struct Struct { void run(int number) { import std.stdio; writeln("run ", number); } } // Pass the object itself. void func1(alias obj)(int number) if (isFunction!(obj.run)) { obj.run(number); } // Pass the object and the name of the method. void func2(alias obj, string method)(int number) if (__traits(compiles, "obj." ~ method ~ "(number);")) { mixin("obj." ~ method ~ "(number);"); } // Pass the method at runtime. void func3(void delegate(int) f, int number) { f(number); } void main() { Struct obj; func1!(obj)(1); func2!(obj, "run")(2); func3(&obj.run, 3); } --- Also, you don't want to name something "Object"; the base class is called Object -- the struct shadows it but you may run into some bug or confusion later. --Ryan
Aug 18 2019