簡體   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