代码如下:使用C++ RTTI模板功能,ACC编译器给编译错误
#include<iostream>
#include<string>
#include<occi.h>
using namespace std; using namespace oracle::occi;
template<class T> void print(T val) {
if (typeid(val).name()==typeid((int)1).name())
{
val+=2;
}
else if (typeid(val).name()==typeid((string())).name())
{
val+="string";
}
cout<<val<<endl; }
int main() {
int a=100;
string str="abcdef";
print(str);
print(a);
return 0;
}
ACC编译如下错误信息:
aCC -AA +DD64 -mt -g -D_DEBUG_ -I/oracle/app1/oracle/product/9.2/rdbms/demo -I/oracle/app1/oracle/product/9.2/rdbms/public -I/oracle/app1/oracle/product/9.2/plsql/public -I/oracle/app1/oracle/product/9.2/network/public -c test4.cpp
Error 203: "test4.cpp", line 16 # Cannot assign 'int' with 'const char *'.
val+="string";
^^^^^^^^
Error 445: "test4.cpp", line 21 # Cannot recover from earlier errors.
int main()
^^^^^^^^^^
*** Error exit code 2
Stop.
因为你的函数希望你得到一个编译错误'val'是一个'int'和'string'在同一时间。模板专业化可以轻松解决这个问题,但这不是你问题的主题。 – Marlon
您应该比较'type_info'对象本身,而不是'name()'的结果 - 但不能保证'name()'对于描述相同类型的不同对象返回相同的结果。 (当然,你不应该在这里使用RTTI,因为类型在编译时是已知的)。 –