gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:34:10 27 4
gpt4 key购买 nike

我有一个函数模板,它接受一个函数作为参数。我希望能够从模板中获取函数参数的名称。一个完整的例子如下。请参阅标记为“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;
}

最佳答案

我要找的是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

这就是我要找的。

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com