如何使用 typeid 存储type_info对象



我正在尝试创建和存储一个type_info对象:

#include <typeinfo>
int i;
type_info x = typeid(i);

并生成错误消息。有什么方法可以存储type_info对象吗?

这背后的历史是,我正在尝试为各种C++整数类型生成测试用例;对它们进行算术并确定中间结果是提升到下一个最大的整数类型还是被截断。那是:

unsigned char x = 257;
unsigned char y = 257;
// is (x + y) == 514 or 256?

并决定对静态数据结构进行类型检查,例如:

int x = <value>;
int y = <value>;
static type_info def = { typeid(bool)
                       , typeid(char),  typeid(unsigned char)
                       , typeid(short), typeid(unsigned short)
                       , typeid(long),  typeid(unsigned long)
                       };
type_info obj = typeid(x + y);
for(int i = 0; i < sizeof(def)/sizeof(def[0]); i++) if (obj == def[i]); break;

无论如何,如果没有能够存储type_info结构,就无法完成它,我仍然想了解整数促销。

您可以创建一个type_info对象吗?gcc 4.5.3 实现将赋值作为私有。

是否有资源告知何时执行整数升级?

谢谢

typeid()返回一个const type_info &type_info有一个私有复制构造函数,因此您无法构建所描述的数组。 我找不到任何可以说它们是否持久的东西,但你可以尝试type_info *a[] = { &typeid(int), ... }

在 C++11 中,(gcc 4.5.1 工作)这种事情可能会起作用:

#include <type_traits>
template<typename... Types>
struct Seq {};
template<typename T, typename Seq, typename=void>
struct IndexOf;
template<typename T, typename First, typename... Types>
struct IndexOf<T, Seq<First, Types...>, typename std::enable_if< std::is_same<T, First>::value >::type > {
  enum { value = 0 };
};
template<typename T, typename First, typename... Types>
struct IndexOf<T, Seq<First, Types...>, typename std::enable_if< !std::is_same<T, First>::value >::type > {
  enum { value = 1+IndexOf<T,Seq<Types...>>::value };
};
typedef Seq< bool, char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long > IntegerTypes;
#include <iostream>
int main() {
  int x = 7;
  int y = 10;
  std::cout << IndexOf< decltype(x+y), IntegerTypes >::value << "n";
  // this next line will not compile, because void is not in the IntegerTypes sequence:
  // std::cout << IndexOf< void, IntegerTypes >::value << "n";
}

但你会注意到它不依赖于 x 或 y 的值,只依赖于它们的类型。

请注意,所有逻辑都是在编译时完成的,而不是在运行时完成的。 如果您传递不在列表中的类型,则会收到大量错误消息(其正确解释为"未找到")。 我本可以使错误消息更短,但我很懒。 :)

type_info不是可复制构造的,但是有一个包装器,称为type_index,它是。它还提供了name()hash_code()方法以及比较运算符,因此在大多数情况下,它与type_info的副本一样好 - 甚至更好,因为它是有序的,不像type_info

最新更新