c if-具有模板中的类型
C++ If- with types in a template
我有一个类模板,当类型是整数时,我想做一些事情,并且在字符串和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>
相关文章:
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- if(双精度类型 == 字符类型)
- 编译器错误"在if语句中分配不兼容的类型"
- 是否可以使用"if constexpr"来声明具有不同类型和init-expr的变量
- 在通用 lambda 中使用 constexpr-if 来确定参数的类型
- c if-具有模板中的类型
- IF在非凉亭类型上如何使用措施
- 是否可以使用模板非类型参数使用#if指令?(矢量多合一类)
- 避免在字符串中分支 if-else 以类型调度
- IF-ELSE语句的Lambda表达式的返回类型扣除
- 更改if范围内变量的类型
- 为容器中的不同字符串类型实现编译时"static-if"逻辑
- ifstream::eof在if语句中时抛出类型错误
- 使用if语句选择类型来声明变量C++
- 比较If语句中的数据类型
- 如何在if/else序列中定义未知类型的全局变量
- 我的程序C++找到三角形的类型,我的if-else语句遇到问题
- C++ 计数字符类型(大写、小写、数字、特殊),不带 if-else、三元或开关大小写.任何想法
- 编写 if then else 类型语句的简洁方法
- 在当前的C++和Java中,double类型和float类型:if(x==0.0)是正确的