【问题标题】:Dlang / Passing arguments to delegatesDlang / 将参数传递给代表
【发布时间】:2021-02-04 02:23:30
【问题描述】:

我希望能够存储一个函数以供以后使用可变数量的参数执行。我通过将委托包装在一个类中来做到这一点。传入参数以执行委托时,永远不会收到参数。这种行为的性质是什么?如何让委托接收参数以使用它们执行?


import std.variant;
import std.stdio;

class Callback
{
    bool delegate(...) callback;
    Variant[] params;

    this(T)(T t)
    {
        this.callback = cast(bool delegate(...)) t;
    }
    
    this(T, A...)(T t, A a)
    {
        this.callback = cast(bool delegate(...)) t;
        
        foreach(item;a)
        {            
            Variant temp = item;
            this.params ~= temp;
        }
    }
    
    void exec()
    {
        if(this.params.length)
        {
            writeln("Passed args: ");
            writeln(this.params);
            callback(this.params);
        }
        else
        {
            callback();
        }
        
    }
}

void main()
{
    bool test()
    {
        writeln("Executing first test");
        return false;
    }
    
    bool test2(Variant[] params)
    {
        writeln("Received args: ");
        writeln(params);
        return false;
    }
    
    Callback cb = new Callback(&test);    
    cb.exec();
    
    writeln();
    
    Callback cb2 = new Callback(&test2, "test2 executing", 1);
    cb2.exec();
}

C:\Users\Nulrie\Documents\D>test
Executing first test

Passed args:
[test2 executing, 1]
Received args:
[]

C:\Users\Nulrie\Documents\D>

【问题讨论】:

    标签: parameters delegates arguments parameter-passing d


    【解决方案1】:

    您在构造函数中的转换无效。您不能将任何函数强制转换为 (...),因为在底层传递参数的方式非常不同。在 Linux 上,您的代码实际上是段错误。

    如果您希望存储委托,并且对使用 GC 感到满意,只需使用委托:

    import std.variant;
    import std.stdio;
    
    void main()
    {
        bool test()
        {
            writeln("Executing first test");
            return false;
        }
        
        bool test2(Variant[] params)
        {
            writeln("Received args: ");
            writeln(params);
            return false;
        }
        
        auto cb = () => test();
        cb();
        
        writeln();
        
        auto cb2 = () => test2([Variant("test2 executing"), Variant(1)]);
        cb2();
    }
    

    您有一些变体,例如(...) { /* something */ } 将允许您接受任意参数,但无论如何您都需要将它们包装在 Variant 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      相关资源
      最近更新 更多