获取模板函数类型
Get template function type
我是C++中使用模板的新手,我想根据<
和>
之间使用的类型做不同的事情,所以function<int>()
和function<char>()
不会做相同的事情。我怎样才能做到这一点?
template<typename T> T* function()
{
if(/*T is int*/)
{
//...
}
if(/*T is char*/)
{
//...
}
return 0;
}
您想要使用函数模板的显式专业化:
template<class T> T* function() {
};
template<> int* function<int>() {
// your int* function code here
};
template<> char* function<char>() {
// your char* function code here
};
创建模板专业化:
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.
}
最佳实践涉及标记调度,因为专业化很棘手。
标签调度更容易使用:
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;
}
要详细了解模板,请访问以下链接:http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-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,3> 结构类型函数中的返回类型函数
- 将C++子类成员函数(虚拟实现)传递给 C 类型函数指针
- C++ 这里有一个返回 (24) 的布尔返回类型函数
- 使用SFINAE来检测void返回类型函数的存在
- 使用此类型函数有什么优势
- 为什么此函数通过类型函数指针调用后,呼叫明智地行为
- 如何使用无类型函数指针调用C++成员函数
- 模板返回类型函数如何在C++中工作
- 具有通用类型函数的动态库[C ]
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
- Bon appetit :从 int 返回类型函数在 main() 中打印字符串
- 对于需要其他模板参数的类型函数的部分模板专业化
- c++错误的参数类型-函数指针
- 延迟评估模板类型函数
- 在引用或指针返回类型函数上输入
- 具有指针数据类型的非类型函数模板参数
- STL中使用的C++自定义比较类型(函数谓词与较少结构)
- C++模板基类的非类型函数模板的 using 声明
- 字符串到类型函数,模板专用化使调用统一
- 自由类型函数可以接受 Unicode 文件名吗?