How to declare a template type as parameter to functions

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 3 15:53:40 PST 2014


On Mon, Nov 03, 2014 at 11:43:42PM +0000, Domingo via Digitalmars-d-learn wrote:
> Hello !
> 
> I could not find a clear way that show how to use template types as
> parameter to functions:
> 
> There is a general rule to do it ? On several examples when the return type
> comes from a template I saw the usage of "auto" where the compiler will
> deduce the correct type but when we need to pass that value as a parameter
> to a function how we declare then as parameter ?
> 
> 
> //void dummFunction(type<Bson,Bson,Bson> "appender", type<forFromAuto>
> "another templated type")
> 
> void dummFunction(typeforFromAuto "appender", typeforFromAuto "another
> templated type")
> {
> }

Use the typeof operator, for example:

	auto myfunc(...) {
		struct InternalType { ... }
		...
		return InternalType(...);
	}

	void anotherFunc(typeof(myfunc(...)) x) { ... }

	void main() {
		auto x = myfunc(...);
		anotherFunc(x);
	}

Using typeof() everywhere is ugly, though, so you could abstract it away
with an alias:

	auto myfunc(...) { ... }

	alias MyType = typeof(myfunc(...));

	void anotherFunc(MyType x) { ... }

	...

On the other hand, if anotherFunc() doesn't really need to know what
exact type is passed, you could turn it into a template function:

	auto myfunc(...) { ... }

	// Now you can pass anything to anotherFunc:
	void anotherFunc(T)(T x) { ... }

But passing "anything" may cause problems, if anotherFunc expects x to
have certain methods, but it's not guaranteed to have them:

	void anotherFunc(T)(T x) {
		...
		x.method(); // will fail if T is int, for example
		...
	}

In this case you can use a signature constraint to limit the scope of
what anotherFunc will accept:

	auto myfunc(...) { ... }

	void anotherFunc(T)(T x)
		if (is(T.init.method())) // test that T has a method called "method"
	{
		...
		x.method();
		...
	}


T

-- 
Being able to learn is a great learning; being able to unlearn is a greater learning.


More information about the Digitalmars-d-learn mailing list