Wednesday, July 1, 2009

Template argument deduction

The process of determining the types and values of the template arguments from the type of the function arguments is called template argument deduction.

int compare(const int &v1, const int &v2)
{
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}

int compare(const double &v1, const double &v2)
{
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}

int main()
{
compare(1, 0); // ok: binds template parameter to int
compare(3.14, 2.7); // ok: binds template parameter to double
return 0;
}

In the first call, compare(1, 0), those arguments are type int; in the second, compare(3.14, 2.7), they have type double.

No comments:

Post a Comment