获取模板函数类型

Gin*_*as_ 4 c++ templates types function c++11

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

template<typename T> T* function()
{
    if(/*T is int*/)
    {
        //...
    }
    if(/*T is char*/)
    {
        //...
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ans 6

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

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

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

template<> char* function<char>() {
    // your char* function code here
};
Run Code Online (Sandbox Code Playgroud)


Yoc*_*mer 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.
}
Run Code Online (Sandbox Code Playgroud)