Some questions of template D

I recently played with the D language, and I have a quick question about templates.

I insert characters and lines into an existing line in the code and come up with this function:

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

Now I have a few questions.

  • Can I limit the types allowed for the s2 argument (I only need char, wchar, dchar, etc. and their corresponding array values)?

  • Is there a way to define a template that will automatically recognize to add if the arg position is 0? Something like this (which does not compile but gives a 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

+6
templates d
source share
3 answers
+4
source share

For 1, there are actually two places that you can limit to valid types.

The first method before . If a symbol solves several methods, the compiler will try to eliminate as many as it can before it tries to decide which one to use. Template constraints (D2 only) and specialization work at this point. For example:

 string insert(T)(string s1, T s2, uint position) if(isSomeChar!T) // D2 only 

-or -

 string insert(T : dchar)(string s1, T s2, uint position) // D1 or D2 

Another method after . This is where the compiler has already decided to use this particular method. You can do this with static statements. Note that this does not cause the compiler to go "ooh, I should try to find another overload!"; he will simply refuse.

 string insert(T)(string s1, T s2, uint position) { static if( !isSomeChar!(T) ) { pragma(msg, "Error: insert(T): T must be a character type."); static assert(false); } ... } 

One more thing: as far as I know, you cannot * just combine wchars and dchars into a string (which is an array of characters). First you need to encode the character into a string. encode in the std.utf module should do the trick.

+1
source share

As for 2, can't you just use the normal if statement?

0
source share

All Articles