标头c ++ 11中的C ++静态const字符串 [英] C++ static const string in header c++11
问题描述
我想编写一个提供有限的RTTI信息的类.
I'm wanting to write a class that provides limited RTTI information.
现在我想要的是这样的东西
Now what I want is something like this
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标头.那不可能吗?
I get a compile time error though saying I can't initialize the string as it is not a literal type. I was wanting to keep this lib header only. Is that impossible?
推荐答案
要仅将模块保留为标头,您可以使用以下几种选择:
To keep the module as header only you have several options:
-
inline
函数返回值. - 模板化的常量技巧.
- C ++ 11
constexpr
关键字.
inline
functions that return the values.- the templated constant trick.
- C++11
constexpr
keyword.
内联函数示例:
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;
}
};
模板化常量技巧的示例:
Example of the templated constant trick:
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" );
};
使用此解决方案,您无法获取任何这些常量的地址.
With this solution you can't take the address of any of these constants.
免责声明:以上代码都没有在任何C ++编译器附近.
Disclaimer: none of the code above has been near any C++ compiler.
这篇关于标头c ++ 11中的C ++静态const字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!