templates - 一些D模板问题

标签 templates d

我最近一直在研究 D 语言,我有一个关于模板的简单问题。

我将字符和字符串插入到代码中的现有字符串中,并提出了这个函数:

string insert(T)(string s1, T s2, uint position) {
    return s1[0 .. position] ~ s2 ~ s1[position .. $];
}

现在,我有几个问题。

  1. 我可以限制 s2 参数允许的类型(我只想要 char、wchar、dchar 等及其各自的数组值)吗?

  2. 是否有某种方法可以定义模板,以便在位置 arg 为 0 时自动知道要在前面添加?像这样的东西(不能编译,但给出了总体思路):

    string insert(T)(string s1, T s2, uint position) {
      static if (position == 0)
        return "" ~ s2 ~ s1;
      else
        return s1[0 .. position] ~ s2 ~ s1[position .. $];
    }
    

谢谢

最佳答案

  1. 是 - 使用 template parameter specializationtemplate constraints (相当于 C++1x 概念)。
  2. static if 意味着可以在编译时计算条件。函数参数不能,因此要么使用常规 if 要么将 position 设为模板参数。

关于templates - 一些D模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1613963/

相关文章:

d - 在 D 中解析事物的惯用方法是什么?

api - D 中基于任务的并行性

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

exception - listener.d : crashes upon unclean disconnect

javascript - 为什么 shift() 对一个数组起作用,但对另一个数组不起作用,除非一般应用于另一个数组

c++ - 模板成员函数的实例化

c++ - Edge-case : When (only) reversing order of template parameters in specialization, 是否可以达到非专用版本?

d - 在 D 中将成员函数作为模板参数传递

c++ - CMake 生成的 DLL 和 Curiously Recurring 模板 (C++) 的不正确行为

.net - 方法返回类型的 Resharper 模板宏