C++ Solution (templates):
C++ introduced function templates and class templates. Since we are only looking at function templates in this question.
Function Templates are functions that can operate with generic types. i.e the functionality of Function templates can be adapted to more than one type (class is also a type) without repeating the entire code for each type.
The above function to compute sum will be written as
template T sum(T a, T b) { return a + b; }
If we call sum for int values, then compiler will generate the below function definition for us
int sum(int a, int b) { return a+b; }
If we call sum for float values, then compiler will generate the below function definition for us
float sum(float a, float b) { return a+b; }
i.e Compiler will use the function Template to generate the actual function definition during compilation. From developer point of view, we have to write just one function template.
In case of conflict in the type of parameters, you may use the below(explicit) syntax to call template function
int p; double q; sum<double>(p, q); //Compiler can't determine the mixed type
1 Comment
Great goods from you, man. I’ve understand youir stuff previous to
and you’re just too fantastic. I really like
what you’ve acquired here, certainly like what you’re
stating and the way bby which you are saying
it. You mwke it enjoyable and you continue to care for to keep
it sensible. I can not wait to read far more from you.
That is actually a great website.