我想编写一个提供有限 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/