Get index of string in array at compile time

tcak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 29 09:43:10 PDT 2015


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.


More information about the Digitalmars-d-learn mailing list