【问题标题】:C++ "typeid" error : operator not allowed in a constant expressionC ++“typeid”错误:常量表达式中不允许使用运算符
【发布时间】:2014-07-17 14:38:33
【问题描述】:

我是 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()?

谢谢

【问题讨论】:

  • typeid 不返回整数常量。
  • @chris 那么有没有办法获得 c++ 类型的唯一整数值​​?
  • 我不知道。你打算用这门课做什么?
  • @chris 基本上是从数据库中检索数据并存储字段的类型和值
  • 您应该查看boost::variant 以了解如何正确处理此类问题

标签: c++ types enums


【解决方案1】:

您可以使用重载函数将一组已知类型转换为整数:

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;
}

【讨论】:

    【解决方案2】:

    如果您使用的是 c++11,则可以为您使用的每种类型获取唯一的 hash_code。 Typeid 产生一个type_info 对象,cppreference 有一个很好的example 说明如何使用它。

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 2018-02-28
      • 2016-05-13
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多