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

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

如果我“重构”我的函数以便通过传入的引用返回结果,代码将编译。但它使函数的 api 非常难看。

最佳答案

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

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

关于templates - 从函数返回类型推断模板参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982121/

相关文章:

c++ - 如何在 C++ 中编写一个通用函数,将整数和字符串作为参数并修改它们?

c++ - 存储可变数量的派生类的可变数量的对象并进行深拷贝

node.js - NodeJS 在计算质数时比 D 更快。如何?

c# - 由于泛型类型推断的限制,无法使用泛型来改进 API

android - 如何从 KClass 反射进行 Kotlin 类型推断?

使用模板化类的 C++ 多态克隆。不能将克隆的对象用作函数中的参数

c++ - 如何在整数列表中找到缺失的元素?

DUB:创建两个具有共同代码库的可执行文件

templates - 检查类型是否是模板的实例化

模板参数的 C++ 部分类型推断 - 这可能吗?