我有一个函数模板,它接受函数作为参数。我希望能够从模板中获取函数参数的名称。下面是一个完整的示例。请参阅标记为“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
这就是我正在寻找的。p>
关于templates - 如何获取 D 模板中函数别名的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20039431/