[英]Get template function type
I'm new in using templates in C++, I want to do different things depending on type used between <
and >
, so function<int>()
and function<char>()
won't do the same things. 我是C ++中使用模板的新手,我想根据
<
和>
之间使用的类型来做不同的事情,因此function<int>()
和function<char>()
不会做相同的事情。 How can I achieve this? 我该如何实现?
template<typename T> T* function()
{
if(/*T is int*/)
{
//...
}
if(/*T is char*/)
{
//...
}
return 0;
}
You want to use explicit specialization of your function template: 您想对函数模板使用显式的专业化:
template<class T> T* function() {
};
template<> int* function<int>() {
// your int* function code here
};
template<> char* function<char>() {
// your char* function code here
};
Create 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.
}
Best practices involves tag dispatch, because specialization is tricky. 最佳实践涉及标签分发,因为专业化非常棘手。
Tag dispatch is easier to use quite often: 标签分发更易于使用:
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;
}
template<class T>
T Add(T n1, T n2)
{
T result;
result = n1 + n2;
return result;
}
For In detail understanding of template, go through the below link: http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1 为了更详细地了解模板,请通过以下链接: http : //www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1
you can define overloaded functions something like this: 您可以定义重载函数,如下所示:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.