templates - 如何获取 D 模板中函数别名的名称?

标签 templates d introspection

我有一个函数模板,它接受函数作为参数。我希望能够从模板中获取函数参数的名称。下面是一个完整的示例。请参阅标记为“COMPILE ERROR”的行 - 我尝试过执行各种与此类似的操作,但我不断收到相同的错误,“function throws.thrower (int n) is not callable”。

import std.array;
import std.conv;
import std.format;
import std.stdio;

int thrower(int n)
{
    if(n > 5)
        throw new core.exception.RangeError("too big");
    return n * 2;
}

int thrower2(int x, int y)
{
    int product = x * y;
    if(product > 25)
        throw new core.exception.RangeError("too big");
    return product;
}

void assertThrows(alias fun, E, T...)(T t)
{
    try
    {
        fun(t);

        auto writer = appender!string();
        formattedWrite(writer,
                       "Expected %s to throw %s, but it did not",
// throws.d(32): Error: function throws.thrower (int n) is not callable using argument types ()

                       //fun.stringof, // <<-- COMPILE ERROR
                       "?",
                       E.stringof);

        throw new core.exception.AssertError(writer.data);
    }
    catch(E ex)
    {
        // Success - we got the expected exception - do nothing.
    }
    // We don't catch any other exceptions -- if these occur they will
    // cause a failure directly, or be handled by other test code that
    // may be expecting the exception. Either way we don't want to
    // interfere.
}

int main()
{
    assert(thrower(5) == 10);
    assertThrows!(thrower, core.exception.RangeError)(6);
    assertThrows!(thrower2, core.exception.RangeError)(9, 9);
    assertThrows!(thrower2, core.exception.RangeError)(1, 1); // Should fail

    return 0;
}

最佳答案

我正在寻找的是 std.traits.fullyQualifiedName ;更改此行可以修复编译错误并提供所需的输出。

    formattedWrite(writer,
                   "Expected %s to throw %s, but it did not",
                   fullyQualifiedName!fun,
                   E.stringof);

这给出了问题中程序的输出:

<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb8b4a9bef5bea3b8beabafb2b4b5f59aa8a8bea9af9ea9a9b4a99bafb3a9b4aca8f5bf" rel="noreferrer noopener nofollow">[email protected]</a>(37): Expected throws.thrower2 to throw RangeError, but it did not

这就是我正在寻找的。

关于templates - 如何获取 D 模板中函数别名的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20039431/

相关文章:

d - 如何在 DUB 中进行配置,将具有主要功能的多个输入 D 文件转换为多个输出可执行文件?

java - 如何让 Spring 接受流畅(非 void)的 setter ?

delphi - 有没有办法在 Delphi 6 中自动分配动态创建的组件的事件处理程序?

c++ - 有没有更好的方法来选择正确的方法重载?

c++ - 为什么这个函数指针的可变参数模板参数推导失败?

stream - D:那溪流呢?

functional-programming - D中的模式匹配

namespaces - 如何列出 TCL 实例中的所有命名空间?

c++ - 确定类型是否具有特定的成员函数签名

java - 将带有通配符的 Java 泛型编译为 C++ 模板