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

时间:2011-06-06 06:55:48

标签: 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();
}

我想知道如何使用类似模板的机制来避免这种重复。如果我正确理解“专业化”,那么两次专业函数的代码是不是可以避免?

5 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:4)

我相信不需要模板专业化,你可以使用简单的函数重载,如下所示:

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

答案 2 :(得分:3)

最好的方法是将Func作为模板:

template<typename T>
void Func(T input);

重载DoSomethingSpecial...()

void DoSomethingSpecial(std::string);
void DoSomethingSpecial(int);
void DoSomethingSpecial(std::vector<int>);

答案 3 :(得分:3)

作为一种风格问题,您可能希望将不同的部分绘制为更容易专门化的普通模板类。作为此技术的示例,请考虑您最喜欢的无序集(或hash_set)的模板实现。这样的实现要求您专门化一个简单的hash_key&lt; T>模板,如果没有专业化可用。它们不要求您专门化整个容器。

虽然你的例子很简单,只需专门化整个函数,但一般来说我会实现Func&lt; T>一般而且专门化DoSomethingSpecial&lt; T>像这样:

template< class T >
void DoSomethingSpecial(T &input)
{
...
}

template< class T >
void Func(T input)
{
DoSomethingGeneral1();
...
DoSomethingSpecial(T);
...
DoSomethingGeneral2();
}

template<>
void DoSomethingSpecial(std::string &input)
{
...
}

template<>
void DoSomethingSpecial(int &input)
{
...
}

答案 4 :(得分:1)

声明通用版本,但仅定义特化:

template<class T>
void DoSpecificStuff( T& withWhat );

template<>
void DoSpecificStuff( int& withWhat)
{
    //implementation
}

template<>
void DoSpecificStuff( std::vector<int>& withWhat)
{
    //implementation
}