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

时间:2013-11-18 03:11:00

标签: templates d introspection

我有一个函数模板,它接受一个函数作为参数。我希望能够从模板中获取函数参数的名称。下面是一个完整的例子。看到标记为“COMPILE ERROR”的行 - 我试图做各种与此类似的事情,但我一直得到同样的错误,“函数throws.thrower(int n)不可调用”。

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;
}

1 个答案:

答案 0 :(得分:3)

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

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

这为问题中的程序提供了输出:

core.exception.AssertError@throws.d(37): Expected throws.thrower2 to throw RangeError, but it did not

这就是我要找的。