String literal arguments

Yao G. nospamyaoltzin at gmail.com
Tue Apr 6 22:23:12 PDT 2010


Hello.

I'm trying to learn more of D templates, but I'm stuck with an issue I  
cannot resolve. Well, actually, I don't know if this is even allowed, and  
that's why I'm posting here. Suppose I have a function declared like this:
---
import std.traits;

void foo(T...)(T args) if( isSomeString!(T[0]) )
{
	/// Some random code.
}
---

and then I call it:
---
auto first  = 1;
auto second = 2;

foo( "Hello World", first, second );
---

You can notice that the first argument is a string literal. What I want to  
know is: If a function argument is declared as a string literal, it can be  
accessed at compile time? And if the answer is yes, how can I do it?.  
Currently, if within the function body I attempt this:
---
// Silly example. Actually I have something a little more complex.
static if( args[0].length > 0 ) {
	// ...
}
---

The compiler complains that the above code cannot be evaluated at C.T.  
Even if the argument is a string literal. The only way that I can make  
this work is if I rewrite the function to:
---
void foo(string str, T...)(T args) if( isSomeString!(T[0]) )
{
	// This works well
	static if( str.length > 0 ) {
		// ...
	}
}
---

But then I would have to write the function calls like this:
---
foo!("Hello World")(first, second);
---

And honestly, I like more the former way. Not a big deal if you look  
objectively, but well, I cannot resist to bikeshed myself.

I hope to make some sense. Cheers!


More information about the Digitalmars-d-learn mailing list