Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates for code which is similar but not identical?

Tags:

c++

templates

I have a bunch of functions which read completely identical except for one line of code, which is different depending on the type of input parameter.

Example:

void Func(std::vector<int> input)
{
   DoSomethingGeneral1();
   ...
   DoSomethingSpecialWithStdVector(input);
   ...
   DoSomethingGeneral2();
}

void Func(int input)
{
   DoSomethingGeneral1();
   ...
   DoSomethingSpecialWithInt(input);
   ...
   DoSomethingGeneral2();
}

void Func(std::string input)
{
   DoSomethingGeneral1();
   ...
   DoSomethingSpecialWithStdString(input);
   ...
   DoSomethingGeneral2();
}

I wonder how I could avoid this duplication using a template-like mechanism. If I understand "specialization" correctly, it does not avoid to have the code of the specialized functions twice?

like image 438
Jakob S. Avatar asked Jun 06 '11 06:06

Jakob S.


People also ask

How do you avoid repetition in code?

To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.

What is duplicate code called?

Sequences of duplicate code are sometimes known as code clones or just clones, the automated process of finding duplications in source code is called clone detection.

What is generic programming templates?

Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.


2 Answers

here you go.. changed the parameters to references to avoid copies + assure you can use the changed values again in Func()

void DoSomethingSpecial( std::vector<int>& input ){}

void DoSomethingSpecial( int& input ){}

void DoSomethingSpecial( std::string& input ){}

template< typename T >
void Func( T input )
{
  DoSomethingGeneral1();
  DoSomethingSpecial(input);
  DoSomethingGeneral2();
}
like image 185
stijn Avatar answered Nov 15 '22 12:11

stijn


I believe there is no need for template speciaization, you can use simple function overloading, something like this:

void DoSomethingSpecial(const std::vector<int>& input)
{
}

void DoSomethingSpecial(string s)
{
}

void DoSomethingSpecial(int input)
{
}
template <typename T>
void Func(const T& input)
{
  //DoSomethingGeneral1();
   DoSomethingSpecial(input);
   //DoSomethingGeneral2();
}

int main()
{
    std::vector<int> a;
    Func(a);
    Func("abc");
    Func(10);
}
like image 23
Naveen Avatar answered Nov 15 '22 12:11

Naveen