August 18, 2019 Problem with aliasing member function | ||||
---|---|---|---|---|
| ||||
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?
|
August 18, 2019 Re: Problem with aliasing member function | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andrey | 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
|
Copyright © 1999-2021 by the D Language Foundation