2011-06-06 80 views
6

我有一堆函数读取完全相同,除了一行代码,根据输入参数的类型不同而不同。代码相似但不完全相同的代码模板?

例子:

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

我不知道如何能使用类似模板的机制避免这种重复。如果我正确理解“专业化”,它不会避免将专业功能的代码重复两次?

+1

我们不能采取大胆的步骤除非知道DoSomethingSpecial真的应该做什么。你能提供更多细节吗?如果不适合模板化它,我们将不得不采取一些措施使其在一般接口内部进行调整,并从调用者的角度对其进行调整。 – sarat 2011-06-06 07:00:57

回答

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

声明一个通用版本,但只能定义专业:

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

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

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

,最好的办法就是让Func为模板:

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

和过载的DoSomethingSpecial...():这里

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

我认为没有必要为模板speciaization,您可以使用简单的函数重载,是这样的:

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

谢谢 - 我简直不敢相信这会起作用,但它确实! :) – 2011-06-06 07:21:10

3

作为一个风格问题,您可能想要绘制出不同的部分作为一个更容易专门化的普通模板类。作为这种技术的一个例子,考虑一下您最喜欢的无序集(或hash_set)的模板实现。如果没有可用的专业化,这种实现需要专门设计一个简单的hash_key < T>模板。他们不要求你专门制作整个容器。

虽然你的例子是很简单的,只是专注的整体功能,一般我会实现Func键< T>一般和专业DoSomethingSpecial < 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) 
{ 
... 
} 
+0

我会考虑这一点,谢谢。 – 2011-06-06 07:21:24

相关问题