C++ "typeid"错误:常量表达式中不允许使用运算符

C++ "typeid" error : operator not allowed in a constant expression

本文关键字:不允许 运算符 常量 typeid 错误 C++ 表达式      更新时间:2023-10-16

我是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提供了一个很好的例子来说明如何使用它。