C++ 当类型未知时调用模板方法
我有C++ 当类型未知时调用模板方法,c++,templates,C++,Templates,我有模板方法,但我不知道类型。我设法得到了对象的类型,现在我得到了bigif-elseloop-like if ( type == "char") { templateMethod<char>(); } else if ( type == "int" ) { templateMethod<int>(); } ..... if(type==“char”){ templateMethod(); }else if(type==“int”){ templateM
模板方法
,但我不知道类型。我设法得到了对象的类型,现在我得到了bigif-else
loop-like
if ( type == "char") {
templateMethod<char>();
} else if ( type == "int" ) {
templateMethod<int>();
}
.....
if(type==“char”){
templateMethod();
}else if(type==“int”){
templateMethod();
}
.....
是否有任何
模板技巧
来避免如此大的if循环
。我的代码现在变得非常丑陋。 实际上,你不需要明确地确定C++中对象的类型。这正是模板的作用
您只提供了一小部分代码,但我认为最容易解决问题的方法是让templateMethod将您当前确定的对象类型作为参数,即使它不使用该对象
因此,不是:
template <typename T> void templateMethod() {
// ...
}
// later
if ( type_of_x == "char") {
templateMethod<char>();
} else if ( type_of_x == "int" ) {
templateMethod<int>();
}
模板void templateMethod(){
// ...
}
//后来
如果(类型为字符){
templateMethod();
}else if(类型x==“int”){
templateMethod();
}
这样做:
template <typename T> void templateMethod(T x) {
// ...
}
// later
templateMethod(x);
模板无效模板方法(T x){
// ...
}
//后来
模板法(x);
这将导致编译器自动调用
templateMethod
,模板类型T
等于x
的类型,即当前代码中试图确定其类型的变量。模板专用化:
template <typename T> void templateMethod() {}
template <> void templateMethod<char>() {
}
template <> void templateMethod<int>() {
}
模板void templateMethod(){}
模板void templateMethod(){
}
模板void templateMethod(){
}
我觉得模板就是为了解决这个问题,但是在编译时。你能提供一些关于你想要达到的目标的更多信息吗?未知的类型?未知的类型?不知道这一点信息就说什么有点困难。根据答案,推荐的方法可能是“使用虚拟函数”,或者其他方法。