I have 2 templated functions (overloaded) with similar functionality except for one line of difference in the function body and one extra function argument. Is it possible to combine the functions further to avoid the duplicate code
template <class T> int MyClass::function1(string name, T& value)
{
// same lines
// if statement
// statement to execute
// else
// different line, calls another function
return 1;
}
template <class T> int MyClass::function1(string name, T& value,
T defaultValue)
{
// same lines
// if statement
// statement to execute
// else
// different line, assign default value to value
return 1;
}
You could give defaultValue
a default argument:
template <class T> int MyClass::function1(string name, T& value,
T defaultValue = T() )
{
if (defaultValue == T() )
//Do something
else
//Do something else
return 1;
}
This way you can call the function with either two or three arguments, but the code will be able to tell how many were supplied. You may need to pick a different value for the default parameter, depending on your situation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments