2013-08-20 57 views
4

我是C++中使用模板的新手,我想根据<>之间使用的类型做不同的事情,所以function<int>()function<char>()不会做同样的事情。 我该如何做到这一点?获取模板函数类型

template<typename T> T* function() 
{ 
    if(/*T is int*/) 
    { 
     //... 
    } 
    if(/*T is char*/) 
    { 
     //... 
    } 
    return 0; 
} 
+1

在你的情况,其中'T'无法从通话可以推断,专业有去(如答案建议)的方式。但是,如果你实际上在参数中使用了'T'并且推导出它,那么最好使用简单的重载和[避免函数模板特化](http://www.gotw.ca/publications/mill17.htm) 。 – Angew

回答

6

你想用你的函数模板的显式特:

template<class T> T* function() { 
}; 

template<> int* function<int>() { 
    // your int* function code here 
}; 

template<> char* function<char>() { 
    // your char* function code here 
}; 
+0

为什么不只是超负荷?重载通常比函数模板专门化更受欢迎。 –

+1

你不能只是返回值超载 –

+0

“为什么不只是超载?”您只能在参数类型上重载,而不能在返回类型上重载。 – utnapistim

5

创建template specializations

template<typename T> T* function() 
{ 
//general case general code 
} 

template<> int* function<int>() 
{ 
    //specialization for int case. 
} 

template<> char* function<char>() 
{ 
    //specialization for char case. 
} 
+0

@billz。是的,你有编译器吗?模板专门化,并明确指定模板参数。 –

-1

可以定义重载函数是这样的:

#define INTT 0 
#define CHARR 1 
template<typename T> 
T* function() 
{ 
int type; 
type = findtype(T); 
//do remaining things based on the return type 

} 

int findType(int a) 
{ 
return INTT; 
} 

int findType(char a) 
{ 
return CHARR; 
} 
1

的最佳实践包括标签调度,因为专业化是棘手的。

标签调度更容易经常使用:

template<typename T> 
T* only_if_int(std::true_type is_int) 
{ 
    // code for T is int. 
    // pass other variables that need to be changed/read above 
} 
T* only_if_int(std::false_type) {return nullptr;} 
template<typename T> 
T* only_if_char(std::true_type is_char) 
{ 
    // code for T is char. 
    // pass other variables that need to be changed/read above 
} 
T* only_if_char(std::false_type) {return nullptr;} 
template<typename T> T* function() 
{ 
    T* retval = only_if_int(std::is_same<T, int>()); 
    if (retval) return retval; 
    retval = only_if_char(std::is_same<T, char>()); 
    return retval; 
} 
+0

这是更通用的。但我知道“专业化是棘手的”部分。为什么它很棘手?你能否把这个部分也添加到答案中。我可以将这个答案作为ref ?.谢谢 –

+0

@Kroushik函数的专门化很棘手,因为它很容易出错!专业化*看起来有点像重载,但它不是超载,它运行在不同的规则上。超载和专业化的重叠会导致严重的脑筋急转弯“为什么不这样做”的问题。标签调度避免了这个问题,因为它没有专门化,而是使用重载调度来完成这项工作,这减少了你需要记住的C++标准的页数,以了解将要发生的事情。 – Yakk