Template function that accept strings and array of strings

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 16 11:41:46 PDT 2015


On Wednesday, 15 July 2015 at 21:57:50 UTC, badlink wrote:
> Hello, I can't figure how to write a template function that 
> accept either strings or array of strings.
>
> This is my current code:
>
> bool hasItemParent(T)(const(char)[] itemId, const(T)[] parentId)
> if (is(typeof(T) == char) || (isArray!T && is(typeof(T[]) == 
> char)))
> {...}
>
> I used const(T)[] because I'd like to accept immutable and 
> mutable strings.
> But calling it with an immutable string generate this error:
>
> Error: template cache.MetadataCache.hasItemParent cannot deduce 
> function from argument types !()(string, string), candidates 
> are:
> cache.MetadataCache.hasItemParent(T)(const(char)[] itemId, 
> const(T)[] parentId) if (is(typeof(T) == char))
>
> Any suggestions ?

Something like this:


import std.stdio;
import std.traits;
import std.range;

bool hasItemParent(A, B)(A itemId, B parentId)
if (isSomeString!(A) && (isSomeString!(B) || isArray!(B) && 
isSomeString!(ElementType!(B))))
{
	writefln("%s", typeof(parentId).stringof);
	return true;
}

void main(string[] args)
{

	string one             = "foo";
	char[] two             = "foo".dup;
	const(char)[] three    = "foo";
	immutable(char)[] four = "foo";

	string[] five             = ["foo", "bar"];
	char[][] six              = ["foo".dup, "bar".dup];
	const(char)[][] seven     = ["foo", "bar"];
	immutable(char)[][] eight = ["foo", "bar"];

	hasItemParent(one, one);
	hasItemParent(two, two);
	hasItemParent(three, three);
	hasItemParent(four, four);

	hasItemParent(one, five);
	hasItemParent(two, six);
	hasItemParent(three, seven);
	hasItemParent(four, eight);
}



More information about the Digitalmars-d-learn mailing list