Get index of string in array at compile time

Timon Gehr via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 29 09:55:22 PDT 2015


On 05/29/2015 06:43 PM, tcak wrote:
> I have define an immutable string array:
>
> [code]
> immutable string[] placeHolderDefinitionList = [
>      "<!-- fullname -->",
>      "<!-- list item -->"
> ];
> [/code]
>
> I need to get index of a string at compile time. So I have written a
> function as below:
>
> [code]
> public size_t getPlaceholderIndex(string PlaceHolderText)( size_t
> lookIndex = 0 ){
>      static if( lookIndex >= placeHolderDefinitionList.length )
>          return size_t.max;
>
>      static if( placeHolderDefinitionList[lookIndex] == PlaceHolderText )
>          return lookIndex;
>      else
>          return getPlaceholderIndex( lookIndex + 1 );
> }
> [/code]
>
> Called it as below:
>
> [code]
> writeln( "Index: ", getPlaceholderIndex!"<!-- list item -->"( 0 ) );
> [/code]
>
> Compiler didn't like my code. It said those things to my face:
>
> main.d(22): Error: variable lookIndex cannot be read at compile time
> main.d(25): Error: variable lookIndex cannot be read at compile time
> main.d(28): Error: template main.getPlaceholderIndex cannot deduce
> function from argument types !()(ulong), candidates are:
> main.d(21):        main.getPlaceholderIndex(string
> PlaceHolderText)(size_t lookIndex = 0)
> main.d(105): Error: template instance main.getPlaceholderIndex!"<!--
> list item -->" error instantiating
>
> This is my first try with this type of code. So I am confused a little
> about what I should be doing.

The easiest way is to just write runtime code and evaluate it via CTFE:

immutable string[] placeHolderDefinitionList = [
     "<!-- fullname -->",
     "<!-- list item -->"
];

void main(){
     import std.stdio, std.algorithm;
     enum index=placeHolderDefinitionList.countUntil("<!-- list item -->");
     writeln("Index: ", index);
}

If you never need the placeHolderDefinitionList at runtime, make it enum 
instead of immutable.



More information about the Digitalmars-d-learn mailing list