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

What is c++ programming language?

549


Do you know about latest advancements in C++ ?

636


List different attributes in C++?

620


What is a forward referencing and when should it be used?

553


which operator is used for performing an exponential operation a) > b) ^ c) none

584






What methods can be overridden in java?

644


If all is successful, what should main return a) 0 b) 1 c) void

534


What character terminates all character array strings a) b) . c) END

645


Write a Program to find the largest of 4 no using macros.

562


Mention the storage classes in c++.

614


How many different levels of pointers are there?

629


Which c++ operator cannot overload?

524


declare an array of structure where the members of the structure are integer variable float variable integer array char variable access all elements of the structure using dot operator and this pointer operator

1722


What is else syntax in c++?

619


What is the use of data hiding?

566