我最近一直在研究 D 语言,我有一个关于模板的简单问题。
我将字符和字符串插入到代码中的现有字符串中,并提出了这个函数:
string insert(T)(string s1, T s2, uint position) {
return s1[0 .. position] ~ s2 ~ s1[position .. $];
}
现在,我有几个问题。
我可以限制 s2 参数允许的类型(我只想要 char、wchar、dchar 等及其各自的数组值)吗?
是否有某种方法可以定义模板,以便在位置 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 .. $]; }
谢谢
最佳答案
- 是 - 使用 template parameter specialization或template constraints (相当于 C++1x 概念)。
static if
意味着可以在编译时计算条件。函数参数不能,因此要么使用常规if
要么将position
设为模板参数。
关于templates - 一些D模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1613963/