【问题标题】:infer template argument type from function return type从函数返回类型推断模板参数类型
【发布时间】:2015-08-13 07:30:56
【问题描述】:

我希望这段代码能够编译,但事实并非如此。

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很丑。

【问题讨论】:

    标签: templates d type-inference


    【解决方案1】:
    unittest {
        auto r = tryMe!string();
        assert(r == "Hello!");
        auto v = tryMe!int();
        assert (v == 42);
    }
    

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

    【讨论】:

    • 你是对的,类型推断从不考虑调用的上下文。重载也是如此:例如,您不能在返回类型上重载。
    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多