3
我希望此代码能够编译,但它不会。从函数返回类型推断模板参数类型
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非常难看。
你是对的,类型推断决不考虑呼叫的上下文。例如,重载也是如此:返回类型不能重载。 –