我希望这段代码能够编译,但它没有。
ReturnType tryMe(ReturnType)() {
static if (is(ReturnType == int)) {
return 42;
} else static if (is(ReturnType == string)) {
return "Hello!";
} else {
assert(0);
}
}
unittest {
string r = tryMe();
assert(r == "Hello!");
int v = tryMe();
assert (v == 42);
}
如何避免此错误消息?
Error: template app.tryMe cannot deduce function from argument types !()(), candidates are:
app.tryMe(ReturnType)()
如果我“重构”我的函数以便通过传入的引用返回结果,代码将编译。但它使函数的 api 非常难看。
最佳答案
unittest {
auto r = tryMe!string();
assert(r == "Hello!");
auto v = tryMe!int();
assert (v == 42);
}
有人可能会纠正我,但我认为编译器无法从赋值中推断出类型。
关于templates - 从函数返回类型推断模板参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982121/