我有一个将类与数据库结合的遗留 ORM,它在 VS2008 和 VS2012 下编译得很好。我尝试使用 VS2012 代码分析的功能,它给了我编译错误 C2975 和 C2440。我已经提取了相关代码以帮助隔离问题:
#include <string>
#include <vector>
#include <typeinfo>
typedef std::vector<unsigned char> byte_packet;
// RTTI option (/GR) required
template<const std::type_info &ref_type_info> struct _TypeOf { /* blank to cause compile error for unsupported types */ };
template<> struct _TypeOf<typeid(std::string)> { typedef std::string typed; };
template<> struct _TypeOf<typeid(int)> { typedef int typed; };
template<> struct _TypeOf<typeid(unsigned int)> { typedef unsigned int typed; };
template<> struct _TypeOf<typeid(double)> { typedef double typed; };
template<> struct _TypeOf<typeid(byte_packet)> { typedef byte_packet typed; };
template<> struct _TypeOf<typeid(time_t)> { typedef time_t typed; };
#define TYPEOF(x) _TypeOf<typeid(x)>::typed
int _tmain(int argc, _TCHAR* argv[])
{
int i = 1;
TYPEOF(i) j;
j = i;
return 0;
}
对于每个 template<> 行,我得到以下一对错误:
error C2975: 'ref_type_info' : invalid template argument for '_TypeOf', expected compile-time constant expression
error C2440: 'specialization' : cannot convert from 'int' to 'const type_info &'
看来编译器将 typeid<...> 视为模板的 int 参数。TYPEOF() 宏用于声明与宏参数类型相同的新变量。这个宏嵌入在其他宏中,我愿意接受替代/更好的方法来做到这一点。它按原样工作,但 VS2012 的代码分析功能阻塞,我不知道为什么。
任何帮助表示赞赏。谢谢。