I have a template member function in a class that is called for all bool, double, int and string. I want to carry out few instructions that are common to all the above mentioned data types. But for String last few lines of code is different. So can any one suggest me a better way to carry out this in a same template function.
template< class T>
xyz (t* a)
{
//few lines are common for all types for data
//last 3 lines of code is different for Strings
}
The solution, as often, is to factorize the common behavior and provide a mean to specialize some parts of the algorithm (see the Template Method pattern).
Here, you can do this quite easily by moving the last lines of your function in a function of its own, which can be specialized for certain data types. Remember that when it comes to functions, overloading should be preferred to template specialization.
Of course, your function should have a more descriptive name than the one I used…
You can also do the symmetrical operation: move the common behavior in a function, and overloads the “top-level” function:
If you do not want or cannot create other functions, you can test the type of the parameter:
is_sameis a class template containing a value which is true if its two parameters are the same type, available in TR1, Boost and C++0x. This solution will work only if the code in theifclause is valid for every data types you instantiate the template with. For example, if you use a member function ofstringin theifblock, compilation will fail when instantiating the function with the other data types, since you cannot invoke a method on a primitive type.