Extracting string parameter from template instance received via alias parameter

anonymous via Digitalmars-d digitalmars-d at puremagic.com
Fri Sep 12 13:46:33 PDT 2014


On Friday, 12 September 2014 at 19:44:28 UTC, MrSmith wrote:
> Given the following program:
>
> ---------------------------------
> import std.stdio;
>
> template first(string s)
> {
> 	string first(string par)
> 	{
> 		if (par == s)
> 			return "true";
> 		else
> 			return "false";
> 	}
> }
>
> template second(alias firstInstance)
> {
> 	string second(string par)
> 	{
> 		// this line doesn't work
> 		static if (is(firstInstance : F!(str), alias F, string str))

`is(...)` checks for types. firstInstance isn't a type, it's a
function, so the `is` expression is always false. You can use
std.traits.TemplateArgsOf instead:

                  import std.traits;
                  import std.typetuple;
                  static if(__traits(compiles,
TemplateArgsOf!firstInstance))
                  {
                      alias targs = TemplateArgsOf!firstInstance;
                      static if(is(typeof(targs) ==
TypeTuple!string))
                          writeln("matched ", targs[0]);
                  }

> 		{
> 			writeln("matched ", str);
> 		}
> 		
> 		enum s = "XXX"; // get s from firstInstance
> 		// without parsing strings and using mixins
> 		// something like second(alias C : F!(str), alias F, string 
> str)

You're on the right track:

template second(alias C : F!(str), alias F, string str)
{
          string second(string par)
          {
                  import std.string : icmp;
                  if (icmp(par, str) == 0)
                          return "true";
                  else
                          return "false";
          }
}
	
> 		import std.string : icmp;
> 		if (icmp(par, s) == 0)
> 			return "true";
> 		else
> 			return "false";
> 	}
> }
>
> void main()
> {
> 	writeln(first!"str"("str"));
> 	writeln(second!( first!"str" )("StR")); // should match string 
> from first, but case insensetive
> }
>
> ---------------------------------
>
> How do I extract s parameter of first passed to second via 
> alias parameter. It seems like it is not possible. Or is it?


More information about the Digitalmars-d mailing list