Template functions, can we make it more simple?
monarch_dodra
monarchdodra at gmail.com
Fri Aug 2 13:37:54 PDT 2013
On Friday, 2 August 2013 at 20:34:04 UTC, SteveGuo wrote:
> I'm not an expert on programming language, if I made a naive
> issue, just forgive me:p
Yes, this would have been better asked in .learn, but no matter.
> Can we declare a template function like this?
>
> auto Add(a, b) // Note a, b do not have type, that means a and
> b use template type
> {
> return a + b;
> }
>
> auto Sub(a, int b) // a uses template type, b is fixed to int
> {
> return a - b;
> }
>
> When we call the function,
>
> Add(1, 2); // deduced to be Add(int, int);
> Add(1.5, 2.3); // deduced to be Add(double, double);
> Add(1.5, "Hello"); // compiler error!
>
> Sub(1.5, 1); // deduced to be Add(double, int);
> Sub(1, 1.1); // deduced to be Add(int, int); compiler error,
> double can not converted to int automatically
Types can be deduced automatically, so you can simply write:
auto Add(A, B)(A a, B b);
The type is explicit in the *declaration*, but when you call
"add(1, 2)", the compiler will *deduce* A and B to be int.
Ditto for sub:
auto Sub(A a)(A a, int b);
More information about the Digitalmars-d
mailing list