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.
Can I limit the types allowed for the s2 argument (I only want char, wchar, dchar, etc. and their respective array values)?
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
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With