Problem with aliasing member function
rjframe
dlang at ryanjframe.com
Sun Aug 18 23:43:17 UTC 2019
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
More information about the Digitalmars-d-learn
mailing list