代码的模板类似但不相同?

Jak*_* S. 6 c++ templates

我有一堆函数读取完全相同,除了一行代码,根据输入参数的类型不同.

例:

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();
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用类似模板的机制来避免这种重复.如果我正确理解"专业化",它不会避免两次专用函数的代码?

sti*_*ijn 8

在这里你去..将参数更改为引用以避免副本+确保您可以在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();
}
Run Code Online (Sandbox Code Playgroud)