reducing code using templated functions

G.S

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;
}
Carlton

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Overloading of C++ templated functions

From Dev

Reducing code duplication

From Dev

Reducing the need for xsl:if and code duplications

From Dev

Reducing number of using in C#

From Dev

how to use typedefs in templated functions?

From Dev

Reducing amount of code to add images

From Dev

C++: call non-templated functions of a templated class

From Dev

copy data with reducing the code lines

From Dev

Reducing equations using R

From Dev

float or double in templated code

From Dev

Reducing constructor boiler plate code

From Dev

Reducing code repetition with recurring code in if-else

From Dev

Bind utility and templated functions

From Dev

Reducing amount of code JavaScript

From Dev

C++ using a template parameter pack to invoke multiple templated functions

From Dev

Reducing code duplication in Golang

From Dev

Map of strings and pointers to templated functions

From Dev

reducing redundant jQuery code

From Dev

Reducing redundant window code

From Dev

Reducing amount of code to add images

From Dev

Shortening code using functions

From Dev

Python decorator pattern: reducing code duplication involving inner functions and functools.wraps

From Dev

Reducing the time complexity of the code below

From Dev

Separation of code and reducing repetition

From Dev

Reducing For loops - Code Optimization

From Dev

Reducing template parameter with using or typedef

From Dev

Errors defining templated class functions

From Dev

Reducing code for random lists

From Dev

templated using declaration in templated struct scope