4

我是在 C++ 中使用模板的新手,我想根据<and之间使用的类型做不同的事情,>所以不会做同样的事情。我怎样才能做到这一点?function<int>()function<char>()

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

5 回答 5

6

您想使用函数模板的显式特化:

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

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

template<> char* function<char>() {
    // your char* function code here
};
于 2013-08-20T11:31:01.753 回答
5

创建模板专业化

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.
}
于 2013-08-20T11:30:55.583 回答
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;
}
于 2013-08-20T13:51:44.747 回答
0
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

于 2013-08-20T11:36:20.653 回答
-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;
}
于 2013-08-20T11:40:18.327 回答