本文介紹了c++ - 如何在c ++模板中執行if else依賴類型?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
// template specialization
#include <iostream>
using namespace std;
// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {element=arg;}
T increase () {
//if(T.type==int)//how to do this or something similar?
//do this if an int
return ++element;
//if(T.type==char)
//if ((element>='a')&&(element<='z'))
//element+='A'-'a';
//return element;
}
};
我知道如何編寫模板特化并為 char 類型做一個單獨的整個類定義.
I know how to write a template specialization and do a separate whole class def just for the char type.
但是如果我想在一個代碼塊中處理所有事情怎么辦?
But what if I wanted to handle everything in just one block of code?
如何檢查 T 是 int 還是 char?
How can I check if T is an int or a char?
推薦答案
你可以使用 typeid
:
if (typeid(T) == typeid(int))
或者你可以使用 std::is_same
類型特征:
Or you could use the std::is_same
type trait:
if (std::is_same<T, int>::value)
這篇關于c++ - 如何在c ++模板中執行if else依賴類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!