从函数返回类型推断模板参数类型

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非常丑陋。

1个回答

3
unittest {
    auto r = tryMe!string();
    assert(r == "Hello!");
    auto v = tryMe!int();
    assert (v == 42);
}

有人可能会纠正我,但我认为编译器无法从赋值中推断类型。

2
你说得没错,类型推断从不考虑调用的上下文。同样适用于重载:例如,你不能根据返回类型进行重载。 - Marc Schütz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接