I want to create a calculator
template < typename T >
class Calculator
{
public :
Calculator ( void );
~Calculator ( void );
T add(T a, T b)
{
return ( a + b ) ;
}
};
Now I want to make this Caculator add strings, so add(“Tim”,”Joe”) shall give me “TimJoe” .
Can I use template function specialization for achieving this by making necessary changes to the existing class .
Why would you want to ?
This code outputs “Hello world”. It’s not optimal (
std::stringparameters in theaddmember function are taken by value), but it does not require a specialization to work.EDIT OK, you want specialization, but you can’t just specialize the
addmember function because the function is not template itself. You can either specialize the whole class :Or make the
addmember function template and specialize it :With the second solution, a single
Calculatorinstance will then be able to addint,std::stringor whatever you need (as it’s theaddfunction which is template, not theCalculatorclass itself).