Function template parameter inference from class template argument
Justin Johansson
procode at adam-dott-com.au
Wed Sep 23 06:55:41 PDT 2009
D1.0
If you have a function template of one type parameter, T, that takes a class template of the same type parameter, T, as an argument, then typical template usage scenario goes like this:
/* Class template definition */
class Foo(T) {
}
/* Function template definition */
void bar(T)( Foo!(T) arg) {
// ...
}
/* Instantiation usage */
main()
{
auto foo = new Foo!(float)(); /* line A */
bar!(float)( foo); /* line B */
}
Now since in the main function the compiler knows that T is float at line A, it occurs to me that code noise could be reduced a bit if the compiler could somehow deduce at line B that the function template parameter, T, is float without it having to be explicitly written.
The instantiation usage would now look like this:
/* Less-noisy instantiation usage */
main()
{
auto foo = new Foo!(float)(); /* line A */
bar( foo); /* line B */
}
The only problem is how then to write the function template definition so that T can be defaulted to the class parameter, T, that accompanies Foo.
One idea I had, which of course doesn't work, is to define the function template's argument with the auto keyword and then somehow figure out T from the argument like so:
/* Function template definition */
void bar(T = typeof( arg))( auto arg) {
// ...
}
Since I'm getting used to finding cool features in D that always lets you do stuff you never dreamed of,
and since I have a lot of template instantiation code,
it would be really neat to be able to reduce the noise a bit as outlined above.
Any ideas anybody? (Note D1.0)
Perhaps this is a no brainer and I just goofed up but have given up after a spending way too much time on it thus far.
Thanks all.
Justin Johansson
More information about the Digitalmars-d
mailing list