头文件 c++11 中的 C++ 静态常量字符串

标签 c++ string c++11 entity constants

我想编写一个提供有限 RTTI 信息的类。

现在我想要的是这样的

template<typename T>
struct isGameComponent
{
   public:
   static_assert(false,"If a non-specialized version is created we have problems");
}

template<>
struct isGameComponent<Transform>
{
  public:
  static const char* COMPONENT_TYPE_NAME = "Transform";
  static const uint32_t COMPONENT_TYPE_ID = HashString("Transform"); //constexpr 
};

//Do this a lot more

我收到一个编译时错误,虽然说我无法初始化字符串,因为它不是文字类型。我只想保留这个 lib header 。这不可能吗?

最佳答案

要仅将模块保留为标题,您有多种选择:

  • 内联 返回值的函数。
  • 模板化常量技巧。
  • C++11 constexpr 关键字。

内联函数示例:

template<typename T>
struct IsGameComponent;

template<>
struct IsGameComponent<Transform>
{
    static
    auto componenTypeName()
        -> const char*
    { return "Transform"; }

    static
    auto componentTypeId()
        -> uint32_t
    {
        static uint32_t const theId = hashString("Transform");
        return the_id;
    }
};

模板常量技巧示例:

template<typename T>
struct IsGameComponent;

template< class Dummy_ >
struct C_IsGameComponent_Transform
{
    static char const* const componentTypeName;
    static uint32_t const componentTypeId;
};

template< class D >
char const* const C_IsGameComponent_Transform<D>::componentTypeName = "Transform";

template< class D >
uint32_t const C_IsGameComponent_Transform<D>::componentTypeId  = hashString( "Transform" );

template<>
struct IsGameComponent<Transform>
    : C_IsGameComponent_Transform<void>
{
    // Constants available here.
};

C++11 constexpr 示例(这要求 hashString 是一个 constexpr 函数):

template<typename T>
struct IsGameComponent;

template< class Dummy_ >
struct C_IsGameComponent_Transform
{
    static char const* constexpr componentTypeName = "Transform";
    static uint32_t constexpr componentTypeId = hashString( "Transform" );
};

使用此解决方案,您无法获取任何这些常量的地址。


免责声明:以上代码均未接近任何 C++ 编译器。

关于头文件 c++11 中的 C++ 静态常量字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23637176/

相关文章:

c++ - 填充字符串 vector

c++ - 在 C++ 中捕获 lambda 的全局引用是否会抑制别名优化?

c++ - 为什么 int 对象和函数类型之间存在歧义?

c++ - 将lambda函数存储到std::function中有什么好处?

c# - 使用 C# 将字符串转换为日期时间

c++ - QGLWidget 获取 Windows 的 gl 上下文

c++ - 告诉 C++ 编译器参数没有别名

c++ - 非常非常基本 : Why won't my makefile work

python - 在不同的函数中使用字符串的名称

python - Python 中的字符串关键字搜索