Search code examples
templatesd

Some D template questions


I've been playing around recently with the D language and I have a quick question about templates.

I'm inserting characters and strings into an existing string in code and came up with this function:

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

Now, I have several questions.

  1. Can I limit the types allowed for the s2 argument (I only want char, wchar, dchar, etc. and their respective array values)?

  2. Is there some way to define the template to automatically know to prepend if the position arg is 0? Something like this (which does not compile, but gives the general idea):

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

Thanks


Solution

    1. Yes - using either template parameter specialization or template constraints (equivalent of C++1x concepts).
    2. static if implies that the condition can be calculated at compile time. A function parameter can't be, so either use a regular if or make position a template parameter.