繁体   English   中英

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

[英]C++ static const string in header c++11

我想编写一个提供有限的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标头。 那不可能吗?

要将模块保留为标头,可以使用以下几种方法:

  • inline函数返回值。
  • 模板化的常量技巧。
  • 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示例(这要求hashStringconstexpr函数):

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 ++编译器。

在类声明之外定义那些静态成员:

const char *isGameComponent<Transform>::COMPONENT_TYPE_NAME = "Transform";

const uint32_t isGameComponent<Transform>::COMPONENT_TYPE_ID = HashString("...");

如果将这些定义放在头文件中,则每个转换单元中将具有多个静态变量,这可能会引起一些问题。 如果将它们放在一个cpp文件中,则建议使用一个文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM