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?
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.
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.
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.
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();
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With