On Friday, 2 August 2013 at 20:37:55 UTC, monarch_dodra wrote:
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);

Thanks for reply!

auto Add(A, B)(A a, B b); // Yes, this is the template function declaration of D manner

But I mean if the syntax can be more simple?

auto Add(A, B)(A a, B b); // type A, B appears twice

// Can we just make it more simple?
auto Add(a, b)
{
}

Reply via email to