Call different member functions on object sequence with a generic handler function?
Ali Çehreli
acehreli at yahoo.com
Sat Jun 30 00:16:28 UTC 2018
On 06/29/2018 02:40 PM, Robert M. Münch wrote:
> How does it work if one of the members takes an argument that is deduced
> inside the handler function?
>
>
> On 2018-06-29 18:05:00 +0000, Ali ‡ehreli said:
>
>> Passing a lambda or a string mixin:
>>
>> import std.stdio;
>>
>> class C {
>> void A() {
>> writeln(__FUNCTION__);
>> }
>>
>> void B() {
>> writeln(__FUNCTION__);
>> }
>
> void C(bool flag) {
> writln(__FUNCTION__):
> }
So the others still don't have a parameter?
It's not clear how the general function should know what member function
is being passed. One way is to check the signature of the lambda and
decide to pass the flag or not. The other way is to always pass the flag
but the caller does not use it.
import std.stdio;
class C {
void A() {
writeln(__FUNCTION__);
}
void B() {
writeln(__FUNCTION__);
}
void C(bool flag) {
writeln(__FUNCTION__);
}
}
void handler(alias func)(C[] cs) {
bool flag;
foreach (c; cs) {
func(c, flag); // Always passes the flag
}
}
void main() {
auto cs = [ new C(), new C() ];
// flag is used only sometimes
handler!((o, flag) => o.A())(cs);
handler!((o, flag) => o.B())(cs);
handler!((o, flag) => o.C(flag))(cs);
}
But it started to feel unnatural at this point. What is the exact use
case? Perhaps there are better ways...
Ali
More information about the Digitalmars-d-learn
mailing list