C++ "typeid"错误:常量表达式中不允许使用运算符
C++ "typeid" error : operator not allowed in a constant expression
我是c++新手。我想构造一个包含类型信息和对象值的类,下面是我所做的:
#include <typeinfo>
enum My_Type {
MyInteger = typeid(int); //ERROR
MyDuoble = typeid(double); //ERROR
MyBoolean = typeid(boolean); //ERROR
MyString = typeid(char *); //ERROR
}
template <typename T>
MyClass {
MyClass(T& Value) {
value = Value;
t = typeid(T);
}
T value;
My_Type t;
}
这给了我一个错误"这个操作符不允许在常量表达式中"当我尝试将整数赋值给我的Enum类型时。
我做错了什么?
是否有一个更优雅的方式来实现我想做的,而不是使用typeid()?
谢谢
可以使用重载函数将一组已知类型转换为整数:
int id_of_type( int ) { return 1; }
int id_of_type( double ) { return 2; }
int id_of_type( bool ) { return 3; }
int id_of_type( char * ) { return 4; }
严格基于编译时类型的方式是模板:
template< typename T > struct id_of_type_t; // template declaration
// template instantiations for each type
template<> struct id_of_type_t< int > { static const int value = 1; };
template<> struct id_of_type_t< double > { static const int value = 2; };
template<> struct id_of_type_t< bool > { static const int value = 3; };
template<> struct id_of_type_t< char * > { static const int value = 4; };
// helper function that is slightly prettier to use
template< typename T >
inline int id_of_type( void )
{
return id_of_type_t< T >::value;
}
// get the id by passed value type
template< typename T > void show_id( T )
{
cout << id_of_type_t< T >::value << endl;
}
如果使用的是c++11,则可以为使用的每种类型获得唯一的hash_code。Typeid生成一个type_info对象,cppreference提供了一个很好的例子来说明如何使用它。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 为什么 Clang 不允许"and"作为函数名称?
- 不允许在向量中添加更多元素
- std::带有自定义缓冲区的 iostream 不允许我写入
- Visual Studio 2017 不允许我创建 C++ 专用模板
- 返回时不允许隐式转换
- 在 c++ 中三元运算符中不允许继续(关键字)吗?
- 不允许运算符 const 参数调用 const 成员函数
- C++数组运算符[]不允许?
- 条件运算符不允许程序终止
- 为什么C++不允许在条件运算符中进行隐式列表初始化?
- 为什么c++的设计不允许将lhs对象传递给运算符
- 如何确保此 qi 解析器不允许点运算符之间的空格
- 为什么使用OpenMP不允许使用!=运算符
- 不允许在C++中使用多参数运算符 [] 的根本原因
- ::运算符 new 是不允许在 lambda 表达式中还是编译器错误?(更新!
- 重载模板类中的二进制运算符不允许访问私有数据成员
- C++ "typeid"错误:常量表达式中不允许使用运算符
- 有什么充分的理由C++不允许将 -> 运算符加倍吗?
- 为什么不允许指针的运算符重载工作?