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

时间:2015-08-13 07:30:56

标签: templates d type-inference

我希望这段代码能够编译,但它并没有。

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)()

如果我重构'我的函数所以我通过传入的引用返回结果,代码编译。但它使得这个功能非常难看。

1 个答案:

答案 0 :(得分:3)

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

有人可能会纠正我,但我认为编译器不能从作业中推断出类型。

相关问题