c if-具有模板中的类型

C++ If- with types in a template

本文关键字:类型 if-      更新时间:2023-10-16

我有一个类模板,当类型是整数时,我想做一些事情,并且在字符串和double时做其他事情。我该怎么做?我有这样的方法:

template <typename T> class abc{
    void method(T i)
    {
        if(i is a string)
          do sth
        else if(i is an integer)
          do sth else
        else if(i is a double)
          do sth else else
    }
}

您可以使用模板专业化。

template<typename T>
class A {
    void method(T);
};

,您为想要的类型定义了

类型的专业化
template<> void A<int>::method(int) {}
template<> void A<string>::method(string) {}
template<> void A<float>::method(float) {}

我没有测试此代码,但是您可以在此处找到更多信息http://en.cppreference.com/w/cpp/language/template_specialization

我想做一个列表,并且可以在整数和双倍方面比较a > b,但是我无法使用字符串进行操作-Jakub1998

实际上,您可以比较字符串。但是在一般情况下,您可以模仿std::map的作用,并进行第二个模板参数,该参数是订购两个T S的策略:

template <typename T, typename Compare = std::greater<T>>
class abc {
    void method(T i, T j)
    {
        if(Compare{}(i, j)) {
            // ...
        }
    }
};

请注意默认参数std::greater,如果用户不提供自定义比较器,它将回到调用i > j

template <typename T>
void method(T i){
if(typeid(i) == typeid(string)){
cout << "string" <<endl;
}else if(typeid(i) == typeid(int)){
 cout << "int" <<endl;
}else{
///...
 }
}
int main() {
string a = "";
method(a);
return 0;

}

您应该包括:

#include <typeinfo>