英文:
Can I make a template of this in D somehow?
问题
这部分代码无法正常工作(这是在一个类内部的):
template this(T : U[], U)
{
    this (U[] array)
    {
        static if (is(U:V[],V))  // 数组
        {
            // 在这里处理数组
        } 
        else static if (is(U:V[string],V)) // 哈希表
        {
            // 在这里处理哈希表
        }
    }
}
有办法解决这个问题吗?
英文:
This does not work (this is inside a class):
template this(T : U[], U)
    {
        this (U[] array)
        {
            static if (is(U:V[],V)  // array
            {
            } 
            else static if (is(U:V[string]),V) // hash
            {
            }
            
        }
    }
Is there a way around to get it work?
答案1
得分: 2
你不能以长格式定义一个模板构造函数(根据语法,模板标识符不能是关键字)。你可以这样做:
this(U)(U[] array) {
   // 相同的内容
}
请注意,没有一种有效的方法可以显式实例化这样的构造函数,它必须使用IFTI。
这种情况似乎不需要,但如果你确实需要更多控制模板实例化,你可以使用一个工厂函数。
英文:
You can't define a template constructor long-form (the template identifier cannot be a keyword according to the grammar). You can do it like this:
this(U)(U[] array) {
   // same stuff
}
Note that there is no valid way to explicitly instantiate such a ctor, it must use IFTI.
This case doesn't seem to need it, but if you do need more control over the template instantiation, you can use a factory function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论