【问题标题】:how to call a function passed as argument with its parameters already given in D?如何调用作为参数传递的函数,其参数已在 D 中给出?
【发布时间】:2017-11-22 15:27:15
【问题描述】:

我需要调用一个作为参数传递给另一个函数的函数,并且必须首先将其所需的参数传递给它。在c++中,这个问题是通过一个宏来解决的:

#include <iostream>

#define CALL(x) x; \
                std::cout << "Called!" << std::endl;

void foo(int a, int b)
{
    std::cout << a * b << std::endl;
}

int main()
{
    CALL(foo(9, 8)); // I want to pass 2 int parameters inside 'foo' function call
    system("PAUSE");
}

它的输出:

> 72
> Called!

这正是我需要在 D 中调用函数的方式。有什么想法吗?

编辑: 我需要在 D 中完成此操作。我想在 CALL 中调用“foo”,例如:

CALL(foo(9, 8)) // and not like: CALL(foo, 9, 8)

但我不知道这是如何在 D 中实现的。也许使用 mixin?

【问题讨论】:

  • 是D还是C++的问题?
  • “在 c++ 中,这个问题是用宏解决的”。这不是更好的方法,模板方法更好(但语法略有不同)。
  • @YSC 对不起,如果我没有说清楚,是关于 D。我只举一个例子来说明我是如何在 c++ 中做到的。
  • 这是误导,我在你的问题上浪费了时间,不酷。
  • @YSC 也许你应该在急于回答之前完整阅读这个问题。在第一个版本中,它说“这正是我需要在 D 中调用函数的方式。”我发现很明显这是一个 D 问题,而 C++ 就是展示所需内容的示例。如果你不留下那条尖刻的评论,我不会打扰,但在抱怨提问者的微尘之前,你需要先检查一下自己的眼睛。

标签: d


【解决方案1】:

在 D 中,您可以为此使用 lazy 函数参数。

import std.stdio;

void CALL(lazy void x) {
        writeln("before called");
        x;
        writeln("after called");
}

void foo(int x, int y) {
        writeln(x, " ", y);
}

void main() {
        CALL(foo(3, 5));
}

D 的lazy 参数存储类使编译器将您提供的任何内容包装在一个小的匿名函数中。上面好像你写的:

import std.stdio;

void CALL(void delegate() x) { // note delegate here in long-form syntax
        writeln("before called");
        x();
        writeln("after called");
}

void foo(int x, int y) {
        writeln(x, " ", y);
}

void main() {
        // and this delegate too
        CALL( delegate() { return foo(3, 5); } );
}

但是编译器会为你重写它。这就是为什么我说lazy void - void 有你传递的隐藏函数的返回类型。如果它返回int,您可以改用lazy int

请注意,由于 CALL 函数内部的 x 被重写为隐藏函数,因此调用它两次实际上会计算两次参数:

void CALL(lazy void x) {
        writeln("before called");
        x;
        writeln("after called");
        x;
        writeln("after called again");
}

会做:

before called
3 5
after called
3 5
after called again

注意它是如何两次打印出参数的。实际上,就像 C 宏一样。但是,如果这不是您想要的,只需将其分配给您自己的临时对象:

void CALL(lazy int x) {
    auto tmp = x;
    // you can now use tmp as a plain int
}

【讨论】:

  • 这就是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多