Consider a c++ template funtion
template<class T>
T& Add(T a, T b){return a+b ;}

if this function is called as
T c = Add("SAM", "SUNG");

what will happen? What is the problem in the template
declaration/ How to solve the problem.

Answer Posted / skc

The error is adding Two pointers isn't alowed in C/C++.
The compiler imlicitly treats "SAM" as const char*. We need
to write a function with "explicit" keyword declaration like

explicit char * Add (const char* x1, const char* x2)
{
// check for null pointers.
// allocate strlen(x1)+strlen(x2)+1 using malloc
// say char*a1 = malloc...;
// check if malloc returns null..take corrective actions

// strcpy (a1, x1);
// strcat (a1, x2);
//strcat (a1, '\0');

return a1; // ask the caller to free the memory allocated
// for a1

}

since this function is writen explicit the compiler will
invoke this function and not call the default template
function.
this is what appears to me. haven't coded and verified.

// Regards, SADIQ

Is This Answer Correct ?    4 Yes 4 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How can you link a c++ program to c functions?

622


what are the iterator and generic algorithms.

1461


Is c better than c++?

619


How do you save a c++ program?

559


What are static member functions?

617






What is the meaning of string in c++?

571


What is microsoft c++ redistributable?

614


What is c++ mutable?

705


How static variables and local variablesare similar and dissimilar?

563


What is the difference between strcpy() and strncpy()?

612


What is the difference between a reference and a pointer?

601


How would you obtain segment and offset addresses from a far address of a memory location?

618


Will a catch statement catch a derived exception if it is looking for the base class?

561


How do you flush std cout?

571


What are the advantage of using register variables?

640